1、在.xaml文件中添加TreeView控件
<TreeView Name="treeView">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Name}"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
注释:这里用到TreeView的ItemTemplate属性,通过对HierarchicalDataTemplate进行赋值,实现数据的动态绑定。HierarchicalDataTemplate:是以等级划分的数据模板的意思。
在上面的xaml文件中的Children、Name,在HierarchicalDataTemplate进行树的搭建之前,需要先在cs文件中,定义一个用于绑定的数据源DefinitionNode,如下:
2、数据源的定义
public class DefinitionNode { public string Name { get; set; } public IList<DefinitionNode> Children { get; set; } }上面的两步定义数据源模型及绑定数据
3、定义实际数据
private void Window_Loaded(object sender, RoutedEventArgs e)
{
DefinitionNode dNode = new DefinitionNode()
{
Name = "一级",
Children = new List<DefinitionNode>()
{
new DefinitionNode()
{
Name = "二级",
Children = new List<DefinitionNode>()
{
new DefinitionNode() {Name = "三级" },
new DefinitionNode() {Name = "三级" }
}
}
}
};
DefinitionNode dNode2 = new DefinitionNode()
{
Name = "一级",
Children = new List<DefinitionNode>()
{
new DefinitionNode { Name = "二级" },
new DefinitionNode {Name = "二级" }
}
};
List<DefinitionNode> list = new List<DefinitionNode> { dNode, dNode2 };
treeView.ItemsSource = list;
}
//静态绑定分级
<TreeView HorizontalAlignment="Left" Height="170" Margin="337,99,0,0" VerticalAlignment="Top" Width="100">
<TreeViewItem Header="一级">
<TreeViewItem Header="二级">
<TreeViewItem Header="三级">
</TreeViewItem>
</TreeViewItem>
</TreeViewItem>
<TreeViewItem Header="一级">
<TreeViewItem Header="二级">
<TreeViewItem Header="三级">
</TreeViewItem>
</TreeViewItem>
</TreeViewItem>
</TreeView>
来源:https://www.cnblogs.com/shcLenmon/p/12593729.html