2010-11-30 216 views
4

如果我編程方式創建一個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); 

不過,我想獲得的路徑到達某個節點在TreeView很像在System.Windows.Forms.TreeNode類的FullPath屬性。所以subNode2的路徑是RootNode//SubNode2。我該怎麼做呢?

編輯:我不是在尋找手動解決方案,但我想知道是否有像FullPath等效的訪問器,或者如果我要以錯誤的方式使用WPF TreeView類。例如。我看過DisplayMemberPathSelectedValuePath,但他們似乎沒有提供我以後的結果。

回答

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

請參見下面的代碼。

所以這個函數返回一個堆棧,其中最頂端的項目將是根,最後一個項目將是元素的直接父項。

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