如何从HierarchicalDataTemplate项目获取TreeViewItem? [英] How to get TreeViewItem from HierarchicalDataTemplate item?
问题描述
我有一个TreeView
,它使用HierarchicalDataTemplate
绑定其数据.
I have a TreeView
which uses a HierarchicalDataTemplate
to bind its data.
它看起来像这样:
<TreeView x:Name="mainTreeList" ItemsSource="{Binding MyCollection}>
<TreeView.Resources>
<HierarchicalDataTemplate
DataType="{x:Type local:MyTreeViewItemViewModel}"
ItemsSource="{Binding Children}">
<!-- code code code -->
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
现在,从说完主窗口的代码后面,我想获取当前选择的TreeViewItem
.但是,如果我使用:
Now, from the code-behind of say the main window, I want to get the current selected TreeViewItem
. However, if I use:
this.mainTreeList.SelectedItem;
selectedItem的类型为MyTreeViewItemViewModel
.但是我想获取父"或绑定" TreeViewItem
.我不会将其传递给我的TreeViewItemModel
对象(甚至都不知道如何).
The selectedItem is of type MyTreeViewItemViewModel
. But I want to get the 'parent' or 'bound' TreeViewItem
. I do not pass that to my TreeViewItemModel
object (wouldn't even know how).
我该怎么做?
推荐答案
来自 Bea Stollnitz 关于此的博客条目,请尝试
From Bea Stollnitz's blog entry about this, try
TreeViewItem item = (TreeViewItem)(mainTreeList
.ItemContainerGenerator
.ContainerFromIndex(mainTreeList.Items.CurrentPosition));
这篇关于如何从HierarchicalDataTemplate项目获取TreeViewItem?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!