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