如何检索在WPF树视图中选择的项目?我想在XAML中这样做,因为我想绑定它.
你可能会认为它SelectedItem显然是不存在的只是readonly因此无法使用.
这就是我想要做的:
<TreeView ItemsSource="{Binding Path=Model.Clusters}"
ItemTemplate="{StaticResource ClusterTemplate}"
SelectedItem="{Binding Path=Model.SelectedCluster}" />
Run Code Online (Sandbox Code Playgroud)
我想绑定SelectedItem到我的模型上的属性.
但这给了我错误:
'SelectedItem'属性是只读的,不能通过标记设置.
编辑: 好的,这是我解决这个问题的方式:
<TreeView
ItemsSource="{Binding Path=Model.Clusters}"
ItemTemplate="{StaticResource HoofdCLusterTemplate}"
SelectedItemChanged="TreeView_OnSelectedItemChanged" />
Run Code Online (Sandbox Code Playgroud)
在我的xaml的codebehindfile中:
private void TreeView_OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
Model.SelectedCluster = (Cluster)e.NewValue;
}
Run Code Online (Sandbox Code Playgroud) 这不可能是这么困难.WPF中的TreeView不允许您设置SelectedItem,表示该属性是ReadOnly.我有TreeView填充,甚至在数据绑定集合更改时更新.
我只需要知道选择了什么项目.我正在使用MVVM,因此没有代码隐藏或变量来引用树视图.这是我找到的唯一解决方案,但它是一个明显的黑客,它在XAML中创建了另一个元素,它使用ElementName绑定将自己设置为树视图选定项,然后您必须绑定Viewmodel.关于此问题还有其他几个问题,但没有给出其他有效的解决方案.
我已经看到了这个问题,但是使用给出的答案给出了编译错误,由于某种原因,我无法将混合sdk System.Windows.Interactivity的引用添加到我的项目中.它说"未知的错误系统.窗口没有被预加载",我还没有想出如何通过它.
对于奖励积分:为什么微软会让这个元素的SelectedItem属性ReadOnly?
所以有人建议使用WPF TreeView,我想:"是的,这似乎是正确的方法." 现在,几个小时后,我简直无法相信使用这个控件有多困难.通过一系列研究,我能够使TreeView`控件正常工作,但我找不到"正确"的方法来将所选项目添加到视图模型中.我不需要从代码中设置所选项目; 我只需要我的视图模型就可以知道用户选择了哪个项目.
到目前为止,我有这个XAML,它本身不是很直观.这都在UserControl.Resources标记内:
<CollectionViewSource x:Key="cvs" Source="{Binding ApplicationServers}">
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="DeploymentEnvironment"/>
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
<!-- Our leaf nodes (server names) -->
<DataTemplate x:Key="serverTemplate">
<TextBlock Text="{Binding Path=Name}"/>
</DataTemplate>
<!-- Note: The Items path refers to the items in the CollectionViewSource group (our servers).
The Name path refers to the group name. -->
<HierarchicalDataTemplate x:Key="categoryTemplate"
ItemsSource="{Binding Path=Items}"
ItemTemplate="{StaticResource serverTemplate}">
<TextBlock Text="{Binding Path=Name}" FontWeight="Bold"/>
</HierarchicalDataTemplate>
Run Code Online (Sandbox Code Playgroud)
这是树视图:
<TreeView DockPanel.Dock="Bottom" ItemsSource="{Binding Source={StaticResource cvs}, Path=Groups}"
ItemTemplate="{StaticResource categoryTemplate}">
<Style TargetType="TreeViewItem">
<Setter Property="IsSelected" Value="{Binding Path=IsSelected}"/>
</Style>
</TreeView> …Run Code Online (Sandbox Code Playgroud)