C#WPF中的TreeView目录

我在C#Windows窗体应用程序中有这个代码,但我需要它在WPF中.你有什么想法?

private void button1_Click(object sender, EventArgs e)
{
    ListDirectory(treeView1, "C:\\Users\\Patrik\\Pictures");
}

private void ListDirectory(TreeView treeView, string path)
{
    treeView.Nodes.Clear();
    var rootDirectoryInfo = new DirectoryInfo(path);
    treeView.Nodes.Add(CreateDirectoryNode(rootDirectoryInfo));
}

private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
{
    var directoryNode = new TreeNode(directoryInfo.Name);
    foreach (var directory in directoryInfo.GetDirectories())
    directoryNode.Nodes.Add(CreateDirectoryNode(directory));

    foreach (var file in directoryInfo.GetFiles())
        directoryNode.Nodes.Add(new TreeNode(file.Name));

    return directoryNode;       
}

感谢帮助.

解决方法:

在WPF而不是Nodes属性中是Items属性,而不是TreeNode,您应该使用TreeViewItem(msdn).

   private void ListDirectory(TreeView treeView, string path)
    {
        treeView.Items.Clear();
        var rootDirectoryInfo = new DirectoryInfo(path);
        treeView.Items.Add(CreateDirectoryNode(rootDirectoryInfo));
    }

    private static TreeViewItem CreateDirectoryNode(DirectoryInfo directoryInfo)
    {
        var directoryNode = new TreeViewItem { Header = directoryInfo.Name };
        foreach (var directory in directoryInfo.GetDirectories())
            directoryNode.Items.Add(CreateDirectoryNode(directory));

        foreach (var file in directoryInfo.GetFiles())
            directoryNode.Items.Add(new TreeViewItem { Header = file.Name });

        return directoryNode;

    }
上一篇:c# – 创建自定义TreeView / TreeNode


下一篇:c# – WPF TreeView – 如何在添加/删除节点后刷新树?