WPF下递归生成树形数据绑定到TreeView上

时间:2023-01-29 09:02:04

最终效果图:(用于学习类的效果 图片丑了点,看官莫怪)

WPF下递归生成树形数据绑定到TreeView上

新建窗体 然后在前端适当位置插入如下代码:

  <TreeView x:Name="departmentTree"  Height="" Width="">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Nodes}">
<StackPanel>
<TextBlock VerticalAlignment="Center" FontSize="" Text="{Binding deptName}" Margin="2,0,0,0"></TextBlock>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>

后端代码:

  public class DepartmentModel
{
public List<DepartmentModel> Nodes { get; set; }
public DepartmentModel()
{
this.Nodes = new List<DepartmentModel>();
this.ParentId = ;//主节点的父id默认为0
}
public int id { get; set; }//id
public string deptName { get; set; }//部门名称
public int ParentId { get; set; }//父类id
}
public partial class TestWin : Window
{
public TestWin()
{
InitializeComponent();
this.departmentTree.ItemsSource = getTrees(, getDepts());//数据绑定
} /// <summary>
/// 获取部门列表--测试
/// </summary>
/// <returns></returns>
public List<DepartmentModel> getDepts() {
List<DepartmentModel> dplst = new List<DepartmentModel>(){
new DepartmentModel(){id=,deptName="主部门1",ParentId=},
new DepartmentModel(){id=,deptName="主部门2",ParentId=},
new DepartmentModel(){id=,deptName="主部门1_1",ParentId=},
new DepartmentModel(){id=,deptName="主部门1_2",ParentId=},
new DepartmentModel(){id=,deptName="主部门1_3",ParentId=},
new DepartmentModel(){id=,deptName="主部门1_4",ParentId=},
new DepartmentModel(){id=,deptName="主部门1_5",ParentId=},
new DepartmentModel(){id=,deptName="主部门2_1",ParentId=},
new DepartmentModel(){id=,deptName="主部门2_2",ParentId=},
new DepartmentModel(){id=,deptName="主部门2_3",ParentId=},
new DepartmentModel(){id=,deptName="主部门2_4",ParentId=},
new DepartmentModel(){id=,deptName="主部门1_1_1",ParentId=},
new DepartmentModel(){id=,deptName="主部门1_1_2",ParentId=},
new DepartmentModel(){id=,deptName="主部门1_2_1",ParentId=},
new DepartmentModel(){id=,deptName="主部门1_1_1_1",ParentId=}
};
return dplst;
} /// <summary>
/// 递归生成树形数据
/// </summary>
/// <param name="delst"></param>
/// <returns></returns>
public List<DepartmentModel> getTrees(int parentid, List<DepartmentModel> nodes)
{
List<DepartmentModel> mainNodes = nodes.Where(x => x.ParentId == parentid).ToList<DepartmentModel>();
List<DepartmentModel> otherNodes = nodes.Where(x => x.ParentId != parentid).ToList<DepartmentModel>();
foreach (DepartmentModel dpt in mainNodes)
{
dpt.Nodes = getTrees(dpt.id,otherNodes);
}
return mainNodes;
} }

上述主要代码为【递归生成树形数据】方法

本人第一次写技术博客

望各位高手不吝赐教