Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get FullPath in WPF treeview?

Tags:

c#

wpf

If I create a WPF TreeView programmatically, for example:

// TreeView treeView; <- added in the designer
TreeViewItem rootNode = new TreeViewItem();
rootNode.Header = "RootNode"
treeView.Items.Add(rootNode);

TreeViewItem subNode1 = new TreeViewItem();
subNode1.Header = "SubNode1";
rootNode.Items.Add(subNode1);

TreeViewItem subNode2 = new TreeViewItem();
subNode2.Header = "SubNode2";
rootNode.Items.Add(subNode2);

However, I would like to get the path to a certain node in the treeview much like the FullPath property in the System.Windows.Forms.TreeNode class. So the path for subNode2 would be RootNode//SubNode2. How do I do this?

Edit: I am not looking for the manual solution, however I am wondering if there is an equivalent accessor like FullPath or if I'm going about using the WPF TreeView class in the wrong way. Eg. I've looked at DisplayMemberPath and SelectedValuePath but they don't seem to provide the result I'm after.

like image 330
Seth Avatar asked Jan 22 '23 00:01

Seth


1 Answers

Take a look in my answer here:

Silverlight: Determine parent TreeViewItem?

Determine path then is simple:

public string GetFullPath(TreeViewItem node) 
{
  if (node == null)
    throw new ArgumentNullException();

  var result = Convert.ToString(node.Header);

  for (var i = GetParentItem(node); i != null; i = GetParentItem(i))
    result = i.Header + "\\" + result;

  return result;
}
like image 62
Lex Lavnikov Avatar answered Jan 30 '23 22:01

Lex Lavnikov