TreeViewItem tvi = new TreeViewItem(); 子节点类
tvi.Tag = "123"; //用于存储此对象的一个信息
tvi.Items.Add(); //添加子节点
tvi.IsExpand = true;//wpf中唯一可以控制子节点展开的方法
通过数据绑定来显示所有子目录下的文件夹
<span style="font-size:12px;"><TreeView Name="tv" HorizontalAlignment="Left" Height="300" Margin="60,10,0,0" VerticalAlignment="Top" Width="257">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Children}">
<StackPanel Orientation="Horizontal">
<Image VerticalAlignment="Center" Source="H:\c#\Wpf基础\我的编辑器\img\dir.ico" Width="16" Height="16" Margin="2,2,2,2"></Image>
<TextBlock VerticalAlignment="Center" Text="{Binding title}"></TextBlock>
<StackPanel.ToolTip>
<TextBlock Text="{Binding numberoffile}" TextWrapping="Wrap"></TextBlock>
</StackPanel.ToolTip>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView></span>
这是wpf中xaml中treeview相关设置: treeview.itemtemplate设置了每个节点的模板,hierarchicaldatatemplate 获取数据绑定的集合 实现递归嵌套的主要属性,里面都是一些控件具体属性的绑定
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
static List<Mulu> GetMuluList(string path)//获取一级目录并记录到Mulu对象中返回一个mulu类型的list反省集合
{
if (Directory.Exists(path))
{
List<Mulu> ltml = new List<Mulu>();
string[] arrdir = Directory.GetDirectories(path);
for (int i = 0; i < arrdir.Length; i++)
{
Mulu newml = new Mulu() { title = System.IO.Path.GetFileName(arrdir[i]), path = arrdir[i] };
ltml.Add(newml);
SetMuluChildren(newml);
}
return ltml;
}
else
{
return null;
}
}
static void SetMuluChildren(Mulu ml) //递归设置每个mulu对象path目录下的子文件夹记录到children集合中
{
string[] arrdir = Directory.GetDirectories(ml.path);
ml.numberoffile = Directory.GetFiles(ml.path,"*",SearchOption.AllDirectories).Length;
ml.title += " ("+ml.numberoffile+")";
for (int i = 0; i < arrdir.Length; i++)
{
Mulu newml = new Mulu() { title = System.IO.Path.GetFileName(arrdir[i]),path = arrdir[i]};
ml.Children.Add(newml);
SetMuluChildren(newml);
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
tv.ItemsSource = GetMuluList(@"H:\c#\c++++加强2");
}
}
public class Mulu
{
public string title //记录显示的标题
{
get;
set;
}
public string path //记录完整的目录
{
get;
set;
}
public int numberoffile //记录目录下所有的文件数量 包含子目录
{
get;
set;
}
public List<Mulu> Children //记录子目录
{
get;
set;
}
public Mulu()
{
Children = new List<Mulu>();
}
}
效果图: