在WPF树视图中获取完整路径?

时间:2010-11-30 01:46:50

标签: c# wpf

如果我以编程方式创建WPF TreeView,例如:

// 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);

但是,我想在树视图中获取某个节点的路径,就像FullPath类中的System.Windows.Forms.TreeNode属性一样。因此subNode2的路径为RootNode//SubNode2。我该怎么做?

编辑:我不是在寻找手动解决方案,但是我想知道是否存在类似FullPath的等效访问器,或者我是否会以错误的方式使用WPF TreeView类。例如。我查看了DisplayMemberPathSelectedValuePath,但它们似乎没有提供我想要的结果。

2 个答案:

答案 0 :(得分:6)

在这里看看我的答案:

Silverlight: Determine parent TreeViewItem?

确定路径然后很简单:

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;
}

答案 1 :(得分:3)

见下面的代码。

所以这个函数返回一个堆栈,其中最顶层的项目是root,最后一项是元素的直接父项。

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();

        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);

        TreeViewItem subNode3 = new TreeViewItem();
        subNode3.Header = "SubNode3";
        subNode2.Items.Add(subNode3);  
    }

    public static Stack<TreeViewItem> GetNodeParent(UIElement element)
    {
        Stack<TreeViewItem> tempNodePath = new Stack<TreeViewItem>();
        // Walk up the element tree to the nearest tree view item. 
        TreeViewItem container = element as TreeViewItem;

        while ((element != null))
        {
            element = VisualTreeHelper.GetParent(element) as UIElement;
            container = element as TreeViewItem;
            if(container!=null)
            tempNodePath.Push(container);
        }

        return tempNodePath;
    }

    private void treeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        Stack<TreeViewItem> path = GetNodeParent(e.NewValue as UIElement);
    }
}