2012-01-10 97 views

回答

6

這裏有一個小例子:

public abstract class ViewModel : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

    protected void OnPropertyChanged(string propertyName) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
} 

public class MyViewModel : ViewModel 
{ 
    public ObservableCollection<Item> Items 
    { 
     get 
     { 
      return new ObservableCollection<Item>() 
      { 
       new Item() {DisplayValue = "Item1", IsSelected = false, Sample = "Sample: I am Item1"}, 
       new Item() {DisplayValue = "Item2", IsSelected = true, Sample = "Sample: I am Item2"}, 
       new Item() {DisplayValue = "Item3", IsSelected = false, Sample = "Sample: I am Item3"} 
      }; 
     } 
    } 
} 

public class Item : ViewModel 
{ 
    public string DisplayValue { get; set; } 

    private bool _isSelected = false; 

    public bool IsSelected 
    { 
     get 
     { 
      return _isSelected; 
     } 
     set 
     { 
      _isSelected = value; 
      OnPropertyChanged("IsSelected"); 
     } 
    } 

    private string _sample; 

    public string Sample 
    { 
     get 
     { 
      return _sample; 
     } 
     set 
     { 
      _sample = value; 
      OnPropertyChanged("Sample"); 
     } 
    } 
} 

XAML:

<Window x:Class="WpfApplication93.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:WpfApplication93" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
    <Grid.DataContext> 
     <local:MyViewModel></local:MyViewModel> 
    </Grid.DataContext> 

    <StackPanel> 
     <TreeView x:Name="myTreeView" ItemsSource="{Binding Items}"> 
     <TreeView.ItemContainerStyle> 
      <Style TargetType="{x:Type TreeViewItem}"> 
      <Setter Property="IsSelected" Value="{Binding IsSelected}"></Setter> 
      <Setter Property="Template"> 
       <Setter.Value> 
       <ControlTemplate TargetType="TreeViewItem"> 
        <TextBlock Text="{Binding DisplayValue}"></TextBlock> 
       </ControlTemplate> 
       </Setter.Value> 
      </Setter> 

      <Style.Triggers> 
       <Trigger Property="IsSelected" Value="True"> 
       <!-- if you want to customize the appearance of a selected element do it here --> 
       <Setter Property="FontWeight" Value="Bold" /> 
       </Trigger> 
      </Style.Triggers> 
      </Style> 
     </TreeView.ItemContainerStyle> 
     </TreeView> 

     <Label Content="{Binding ElementName=myTreeView, Path=SelectedItem.Sample}"></Label> 
    </StackPanel> 
    </Grid> 
</Window> 
+0

當我在樹中選擇的項目查看其無法正常工作。 – Tanya 2012-01-10 08:59:26

+0

我添加了雙向綁定模式,所以它現在應該工作 – SvenG 2012-01-10 09:05:12

+0

' '我用上面的代碼,並把斷點上IsSelected設置屬性。它不工作。 – Tanya 2012-01-10 09:08:55