WPF ItemsControl 从数据对象获取容器(TreeView、多选)
如何获取 WPF ItemsControl 中对象的容器。
我正在编写一个带有可绑定 SelectedItem 和 SelectedItems 依赖属性的多选树视图。这么长时间以来,一切都很好。唯一的问题是,当我第二次按下 ctrl 键单击树中的某个项目时,不应选择该项目,而应选择上一次选择的项目。 TreeView 包含一个名为 ChangeSelection 的私有方法。据我了解,第一个参数是 Container,第二个参数是 TreeViewItem,最后一个参数是选择或不选择项目的位置。
我通过捕获 SelectedItemChanged 事件来实现多重选择。
此代码适用于新选定的项目
private void OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
var view = ItemContainerGenerator.ContainerFromItem(e.NewValue) as TreeViewItem;
// ...
}
,但如果我想从 ObservableCollection 中保存的项目获取 TreeViewItem...它将不起作用。
编辑:好的,正如我发现的那样。上面的代码仅适用于第一级项目......
How can I get the Container for an object in WPF ItemsControl.
I am writing a multiselect treeview with bindable SelectedItem und SelectedItems Dependency Properties. So long everything works just fine. The only thing is, when I click on an item in the tree with pressed ctrl a second time this item should not be selected but the last previous selected item. The TreeView contains a private Method called ChangeSelection. As far as i understand the first parameter is the Container, the second is the TreeViewItem and the last wherether the item shall be selected or not.
I implement the multiselection with catching the SelectedItemChanged event.
This code works for the new selected item
private void OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
var view = ItemContainerGenerator.ContainerFromItem(e.NewValue) as TreeViewItem;
// ...
}
BUT if i want to get the TreeViewItem from an item saved in an ObservableCollection... it will not work.
EDIT: Ok, as i found out. The code above works only for the first level of items...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编辑:这个问题的解决方案并不简单。可以使用视图模型(提供诸如 IsSelected、IsExpanded、IsEnabled 和 Parent 等基础知识的接口)来查找选定的树视图项。您可以像这样搜索 TreeViewItem:
EDIT: The solution for this problem isn't trivial. It is possible to find the selected treeview item by using a viewmodel (f.e. an interface which provides basics like: IsSelected, IsExpanded, IsEnabled and Parent). You can search the TreeViewItem like this: