问题描述
如何检索在 WPF-treeview 中选择的项目?我想在 XAML 中这样做,因为我想绑定它.
How can I retrieve the item that is selected in a WPF-treeview? I want to do this in XAML, because I want to bind it.
您可能认为它是 SelectedItem
,但显然 是只读的,因此无法使用.
You might think that it is SelectedItem
but apparently that is readonly and therefore unusable.
这就是我想要做的:
<TreeView ItemsSource="{Binding Path=Model.Clusters}"
ItemTemplate="{StaticResource ClusterTemplate}"
SelectedItem="{Binding Path=Model.SelectedCluster}" />
我想将 SelectedItem
绑定到我的模型上的一个属性.
I want to bind the SelectedItem
to a property on my Model.
但这给了我错误:
'SelectedItem' 属性是只读的,不能从标记中设置.
好的,这就是我解决这个问题的方法:
Ok, this is the way that I solved this:
<TreeView
ItemsSource="{Binding Path=Model.Clusters}"
ItemTemplate="{StaticResource HoofdCLusterTemplate}"
SelectedItemChanged="TreeView_OnSelectedItemChanged" />
在我的 xaml 的代码隐藏文件中:
and in the codebehindfile of my xaml:
private void TreeView_OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
Model.SelectedCluster = (Cluster)e.NewValue;
}
推荐答案
我意识到这已经有一个答案被接受,但我把它放在一起来解决问题.它使用与 Delta 的解决方案类似的想法,但不需要对 TreeView 进行子类化:
I realise this has already had an answer accepted, but I put this together to solve the problem. It uses a similar idea to Delta's solution, but without the need to subclass the TreeView:
public class BindableSelectedItemBehavior : Behavior<TreeView>
{
#region SelectedItem Property
public object SelectedItem
{
get { return (object)GetValue(SelectedItemProperty); }
set { SetValue(SelectedItemProperty, value); }
}
public static readonly DependencyProperty SelectedItemProperty =
DependencyProperty.Register("SelectedItem", typeof(object), typeof(BindableSelectedItemBehavior), new UIPropertyMetadata(null, OnSelectedItemChanged));
private static void OnSelectedItemChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var item = e.NewValue as TreeViewItem;
if (item != null)
{
item.SetValue(TreeViewItem.IsSelectedProperty, true);
}
}
#endregion
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.SelectedItemChanged += OnTreeViewSelectedItemChanged;
}
protected override void OnDetaching()
{
base.OnDetaching();
if (this.AssociatedObject != null)
{
this.AssociatedObject.SelectedItemChanged -= OnTreeViewSelectedItemChanged;
}
}
private void OnTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
this.SelectedItem = e.NewValue;
}
}
然后您可以在 XAML 中使用它:
You can then use this in your XAML as:
<TreeView>
<e:Interaction.Behaviors>
<behaviours:BindableSelectedItemBehavior SelectedItem="{Binding SelectedItem, Mode=TwoWay}" />
</e:Interaction.Behaviors>
</TreeView>
希望对某人有所帮助!
这篇关于数据绑定到 WPF 树视图中的 SelectedItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!