xaml:

<Window x:Class="TreeViewDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="550" Width="825"
        xmlns:local="clr-namespace:TreeViewDemo">
    <Window.Resources>
        <HierarchicalDataTemplate DataType="{x:Type local:Folder}" ItemsSource="{Binding SubFolders}">
            <TextBlock Text="{Binding Name}"/>
        </HierarchicalDataTemplate>
    </Window.Resources>
    <Grid>
        <TreeView ItemsSource="{x:Static local:Data.Folders}" />
    </Grid>
</Window>

cs:

namespace TreeViewDemo
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}

public static class Data
{
private const string RootFolder = @"F:\";

public static IEnumerable<Folder> Folders
{
get
{
return new List<Folder>()
{
new Folder()
{
Name = RootFolder,
SubFolders = EnumerateDirectories(RootFolder)
}
};
}
}

private static IEnumerable<Folder> EnumerateDirectories(string directory)
{
var folders = new List<Folder>();
try
{
foreach (var dir in Directory.EnumerateDirectories(directory))
{
var folder = new Folder() { Name = new DirectoryInfo(dir).Name, SubFolders = EnumerateDirectories(dir) };
folders.Add(folder);
}

return folders;
}
catch (UnauthorizedAccessException)
{
return null;
}
}
}

public class Folder
{
public IEnumerable<Folder> SubFolders { get; set; }
public string Name { get; set; }
}
}

 source code can be downloaded at: https://files.cnblogs.com/bear831204/TreeViewDemo.zip

相关文章:

  • 2022-12-23
  • 2021-09-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-18
  • 2021-11-07
  • 2021-07-10
猜你喜欢
  • 2022-03-04
  • 2021-10-13
  • 2018-10-15
  • 2021-07-21
  • 2021-06-03
  • 2022-12-23
相关资源
相似解决方案