问题:
How can I retrieve the item that is selected in a WPF-treeview?如何检索在 WPF-treeview 中选择的项目? I want to do this in XAML, because I want to bind it.我想在 XAML 中执行此操作,因为我想绑定它。
You might think that it is SelectedItem
but apparently that does not exist is readonly and therefore unusable.您可能认为它是SelectedItem
但显然它不存在是只读的,因此无法使用。
This is what I want to do:这就是我想要做的:
<TreeView ItemsSource="{Binding Path=Model.Clusters}"
ItemTemplate="{StaticResource ClusterTemplate}"
SelectedItem="{Binding Path=Model.SelectedCluster}" />
I want to bind the SelectedItem
to a property on my Model.我想将SelectedItem
绑定到我的模型上的一个属性。
But this gives me the error:但这给了我错误:
'SelectedItem' property is read-only and cannot be set from markup. 'SelectedItem' 属性是只读的,不能从标记中设置。
Edit: Ok, this is the way that I solved this:编辑:好的,这是我解决这个问题的方法:
<TreeView
ItemsSource="{Binding Path=Model.Clusters}"
ItemTemplate="{StaticResource HoofdCLusterTemplate}"
SelectedItemChanged="TreeView_OnSelectedItemChanged" />
and in the codebehindfile of my xaml:在我的 xaml 的代码隐藏文件中:
private void TreeView_OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
Model.SelectedCluster = (Cluster)e.NewValue;
}
解决方案:
参考一: https://stackoom.com/question/4C9g参考二: Data binding to SelectedItem in a WPF Treeview