且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

数据在WPF树视图结合的SelectedItem

更新时间:2023-10-13 18:09:46

该属性存在:TreeView.SelectedItem

但它是只读的,所以你无法通过具有约束力的分配它,只有找回

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.

You might think that it is SelectedItem but apparently that does not exist is readonly and therefore unusable.

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.

But this gives me the error:

'SelectedItem' property is read-only and cannot be set from markup.

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:

private void TreeView_OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
    Model.SelectedCluster = (Cluster)e.NewValue;
}

This property exists : TreeView.SelectedItem

But it is readonly, so you cannot assign it through a binding, only retrieve it