树视图父子完整层次结构

时间:2013-12-05 17:51:51

标签: c# wpf treeview

我为文件夹导航系统创建了以下树视图:

看起来像:

Tree View

我的代码:

string[] RootFolders = Directory.GetDirectories(txtRootDirectory.Text.Trim());

        foreach (string dir0 in RootFolders)
        {
            if (dir0.Contains("_In"))
            {
                TreeViewItem path = new TreeViewItem() { Header = new DirectoryInfo(dir0).Name };

                string[] MainFolder = Directory.GetDirectories(dir0);
                foreach(string dir1 in MainFolder)
                {
                    TreeViewItem path1 = new TreeViewItem() { Header = new DirectoryInfo(dir1).Name };
                    path.Items.Add(path1);

                    string[] SubFolder = Directory.GetDirectories(dir1);
                    foreach (string dir2 in SubFolder)
                    {
                        TreeViewItem path2 = new TreeViewItem() { Header = new DirectoryInfo(dir2).Name };
                        path1.Items.Add(path2);
                    }
                }



                tree.Items.Add(path);
            }
        }

我需要的是能够获取序列中最终子节点的所有父文件夹的名称,并将它们连接在一起以创建目录。例如,如果选择了'ascx Staging Application'树项,我需要返回'ascx Staging Application','Web Applications','_In Development',这样我就可以创建一个用于打开该文件的字符串。 (即“c:_In Development \ Web Applications \ ascx Staging Application.sln”)

到目前为止,我能想出的就是这一切,从这里看,一切似乎都崩溃了......

private void tree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        TreeViewItem trvItem = (TreeViewItem)tree.SelectedItem;

        if (trvItem != null)
        {
            TreeViewItem trvParent = (TreeViewItem)trvItem.Parent;
            MessageBox.Show(trvParent.Header.ToString());
        }
    }

1 个答案:

答案 0 :(得分:0)

一个非常简单的解决方案是将路径分配给每个TreeViewElement的Tag属性。

读取所选路径的代码如下所示:

private void tree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        TreeViewItem trvItem = (TreeViewItem)tree.SelectedItem;

        if (trvItem != null)
        {
            String path = (String)trvItem.Tag;
            MessageBox.Show(path);
        }
    }