【发布时间】:2012-02-26 22:10:54
【问题描述】:
所以有人建议使用 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>
这是树视图:
<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>
这可以按环境(开发、QA、产品)正确显示服务器。但是,我在 SO 上找到了各种获取所选项目的方法,其中许多方法令人费解且困难。是否有一种简单 方法可以将所选项目添加到我的视图模型中?
注意:TreeView 上有一个SelectedItem 属性,但它是只读的。令我沮丧的是只读就可以了。我不想通过代码更改它。但是我不能使用它,因为编译器抱怨它是只读的。
还有一个看似优雅的建议来做这样的事情:
<ContentPresenter Content="{Binding ElementName=treeView1, Path=SelectedItem}" />
我问了这个问题:“您的视图模型如何获取此信息?我知道ContentPresenter 持有所选项目,但我们如何将其传递给视图模型?”但是还没有答案。
所以,我的总体问题是:“有没有一种简单的方法可以将所选项目添加到我的视图模型中?”
【问题讨论】:
标签: wpf mvvm treeview selecteditem