Reputation: 911
I have a TreeView object in my App, that gets filled by a folder hierarchy. I want to try and "climb" up this hierarchy so I can get the currently selected item's path. I have tried to use the DepedencyObject that you get with TreeViewItem.Parent, but I am confused how I can then get the parent as a TreeViewItem itself, so I can continue "climbing" up.
Is there any way to convert the DependencyObject into a TreeViewItem?
Upvotes: 2
Views: 104
Reputation: 791
You can climb up from you childNode (always casting the parent to TreeViewitem unitil its not possible -> root of treeview reached):
string path =(string) ChildItem.Header;
TreeViewItem currentItem = ChildItem;
while (currentItem.Parent is TreeViewItem)
{
currentItem = currentItem.Parent as TreeViewItem;
path = (string) currentItem.Header + "/" + path;
}
Upvotes: 1
Reputation: 23
this will work:
TreeView myTreeview = new TreeView();
//add some nodes here or import.
TreeNode parentnode = myTreeview.SelectedNode.Parent;
//or find a node using:
TreeNode parentnode = myTreeview.Nodes.Find("name"true);
//true searches in all children
//TreeNode.Parent will return null if the node has no parent
or in a method:
public TreeNode getParent(TreeNode node)
{
return node.Parent;
}
Upvotes: 0