我使用的两个类如下
public class FoundDirectory
{
public string fullPath { get; set; }
public string parent { get; set; }
public string directoryName { get; set; }
public ObservableCollection<FoundDirectory> subDirectories { get; set; }
public ObservableCollection<FoundFile> subFiles { get; set; }
public override string ToString()
{
return directoryName;
}
}
public class FoundFile
{
public string fileName { get; set; }
public string fullPath { get; set; }
public long fileLength { get; set; }
public override string ToString()
{
return fileName;
}
}
我正在尝试从递归硬盘扫描生成TreeView。我将一个ObservableCollection传递给TreeView。我可以让它显示正确嵌套的子目录但无法让它显示子文件。我的XAML如下:
<TreeView Name="directoryTree" Grid.Column="0" Grid.Row="1" ItemsSource="{Binding Path=sortedDirList}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=subDirectories}">
<StackPanel>
<TextBlock Text="{Binding Path=directoryName}"/>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
我尝试了多种不同的方式来显示子文件,但似乎没有任何工作
答案 0 :(得分:1)
以下是您可以采用的一种方式:
public class Node
{
public string FullPath { get; set; }
public string Name { get; set;}
public int Size {get;set;}
public ObservableCollection<Node> Children {get; set;}
public string ToString()
{
return Name;
}
}
的Xaml:
<TreeView Name="directoryTree" Grid.Column="0" Grid.Row="1" ItemsSource="{Binding Path=sortedDirList}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Children}">
<StackPanel>
<TextBlock Text="{Binding Path=Name}"/>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
然后只需使sortedDirList成为一个只包含根目录的列表,它应该正确扩展。
注意:类/变量名称只是占位符,可以随意重命名。
要以递归方式填充树,请写下这样的内容:
public void DirectorySearch(Node node)
{
foreach(string f in Directory.GetFiles(node.Name))
{
//initialize a node with the file info
node.Children.Add(fileNode);
}
foreach(var d in Directory.GetDirectories(node.Name)
{
//initialize a node with directory info
node.Children.Add(dirNode);
DirectorySearch(dirNode);
}
}