WPF:TreeView 获取父节点 [英] WPF: TreeView get parent node
问题描述
问题简述:
Node 1
Child x
Child Y
Node 2
Child z
在处理TreeView
类型时,选择父节点时,SelectedItem
属性返回一个TreeViewItem
类型的对象,下面正常工作
When dealing with TreeView
type, when selecting a parent node, the SelectedItem
property returns an object of type TreeViewItem
and the following works properly
TreeViewItem parentNode = (TreeViewItem) treeView.SelectedItem;
This while, this property return a String
when a value of a node is selected which means in that case the following will be true:
This while, this property return a String
when a value of a node is selected which means in that case the following will be true:
Boolean valueType = treeView.SelectedItem is String; --> True
因此,我们不能再将对象转换为 TreeViewItem
.
Accordingly, we cannot cast the object to the TreeViewItem
anymore.
假设你有以下内容
IEnumerable<IGrouping<String, Childs>> treeModel;
并且您想知道子节点属于哪个节点,如何从TreeView
中获取父节点元素.
And you want to know to which node the child belongs, how would you obtain the parent node element from the TreeView
.
推荐答案
不幸的是,SO 中的所有帖子都指出了错误的解决方案,或者由于我解释的原因而可能不再起作用的解决方案.(同样适用于所有 Microsoft 文档,可能已经过时)
Unfortunately all post in SO point out to the wrong solution, or a solution which may no longer work due to the reason I explained. (The same applies to all Microsoft documentation, maybe outdated)
这似乎没有 **Built-In**
功能,所以决定设计我自己的解决方案.这个问题可以通过创建一个自定义的TreeViewItem
类并添加一个ParentNodeValue
属性来解决.
There seems to be no **Built-In**
feature to this, so decided to design my own solution. This problem can be solved, by creating a customized TreeViewItem
class and adding a ParentNodeValue
property.
public class AdvancedTreeViewItem<T>: TreeViewItem{
public T ParentNodeValue {get; set;}
public T RootParentNodeValue {get; set;}
}
我们可以执行以下操作来获取节点值:
And we can do the following to get the node value:
var selectedValue = (AdvancedTreeViewItem<String>)treeView.SelectedItem;
MessageBox.Show(selectedValue.RootParentNodeValue);
在这种方法中,SelectedItem
属性无法返回 String
In this approach, there is no way the SelectedItem
property would return a String
这篇关于WPF:TreeView 获取父节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!