我写了一个WPF活动库。在其中一个活动中,我使用TreeView在其中显示一些信息,如下所示:
...
<TreeView x:Name= "myTreeView" Grid.Row="0" FontFamily="Tahoma" FontSize="10">
<TreeViewItem Header="Item 1">
<TreeViewItem Header="Item 11" >
<TreeViewItem Header="Item 111"/>
<TreeViewItem Header="Item 112" />
</TreeViewItem>
<TreeViewItem Header="Item 12" >
<TreeViewItem Header="Item 121" />
<TreeViewItem Header="Item 122" />
<TreeViewItem Header="Item 123" />
</TreeViewItem>
<TreeViewItem Header="Item 13" >
<TreeViewItem Header="Item 131" />
<TreeViewItem Header="Item 132" />
</TreeViewItem>
</TreeViewItem>
</TreeView>
...
我在Code-Activity中的属性是这样的:
public InArgument<TreeViewItem> Branch {
get{return _branch;}
set
{
if (this._branch != value)
{
this._branch = value;
OnPropertyChanged("Branch");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
我需要当用户点击其中一个TreeView项目,我发送该项目到我的属性(我想把它绑定到分支属性)。我该怎么做呢?
不幸的是,你想要实现的目标并没有开箱操作。这里有一些不同的解决方法:WPF树视图中与SelectedItem的数据绑定
最简单的方法是设置一些CodeBehind:XAML:
<TreeView SelectedItemChanged="myTreeView_SelectedItemChanged"
代码:
private void myTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
var treeViewItem = e.NewValue as TreeViewItem;
(myTreeView.DataContext as MyViewModel).Branch = treeViewItem;
}