新建一个节点类
public class Node
{
public string Name { get; set; }
public List<Node> Children { set; get; }
public Node()
{
Children = new List<Node>();
}
}
新建方法显示树状图
private void ShowTreeView()
{
DirectoryInfo directoryInfo = new DirectoryInfo(@"D:\Dam");
List<Node> nodes = new List<Node>();
Node node = new Node()
{
Name = "所有文件夹"
};
node.Children.Add(GetChildren(directoryInfo));
nodes.Add(node);
}
递归法获取子文件夹
public Node GetChildren(DirectoryInfo directoryInfo)
{
Node node = new Node() { Name = directoryInfo.Name };
var subDirectory = directoryInfo.GetDirectories();
if (subDirectory.Length !=0)
{
foreach (var item in subDirectory)
{
node.Children.Add(GetChildren(item));
}
}
return node;
}
xaml文件添加数据绑定
<TreeView x:Name="tv" HorizontalAlignment="Left" Height="399" Margin="10,10,0,0" VerticalAlignment="Top" Width="232">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}"></TextBlock>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>