Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TreeView directories in C# WPF

I have this code in C# Windows Form Application, but I need it in WPF. Do you have any ideas?

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

Thanks for help.

like image 879
user3271748 Avatar asked Feb 22 '14 12:02

user3271748


People also ask

How do I create a folder in TreeView?

Combine(treeView1. SelectedNode. Tag as string, "New Folder")); This will create a directory which is represented by the combination of the path of the current node and the string 'New Folder'.

What is the use of TreeView?

The TreeView control is used to display hierarchical representations of items similar to the ways the files and folders are displayed in the left pane of the Windows Explorer. Each node may contain one or more child nodes.

What is a tree directory?

A directory tree is a hierarchy of directories that consists of a single directory, called the parent directory or top level directory, and all levels of its subdirectories (i.e., directories within it).


1 Answers

In WPF instead of Nodes property is Items property and instead of TreeNode you should use 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;

    }
like image 110
kmatyaszek Avatar answered Oct 29 '22 12:10

kmatyaszek