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

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

WPF下递归生成树形数据绑定到TreeView上_第1张图片

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

  "departmentTree"  Height="500" Width="500">
                            
                                "{Binding Nodes}">
                                    
                                        "Center" FontSize="14" Text="{Binding deptName}" Margin="2,0,0,0">
                                    
                                
                            
                        

后端代码:

  public class DepartmentModel
    {
       public List Nodes { get; set; }
       public DepartmentModel()
        {
            this.Nodes = new List();
            this.ParentId = 0;//主节点的父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(0, getDepts());//数据绑定
        }


        /// 
        /// 获取部门列表--测试
        /// 
        /// 
        public List getDepts() {
            List dplst = new List(){
            new DepartmentModel(){id=1,deptName="主部门1",ParentId=0},
            new DepartmentModel(){id=2,deptName="主部门2",ParentId=0},
            new DepartmentModel(){id=3,deptName="主部门1_1",ParentId=1},
            new DepartmentModel(){id=4,deptName="主部门1_2",ParentId=1},
            new DepartmentModel(){id=5,deptName="主部门1_3",ParentId=1},
            new DepartmentModel(){id=6,deptName="主部门1_4",ParentId=1},
            new DepartmentModel(){id=7,deptName="主部门1_5",ParentId=1},
            new DepartmentModel(){id=8,deptName="主部门2_1",ParentId=2},
            new DepartmentModel(){id=9,deptName="主部门2_2",ParentId=2},
            new DepartmentModel(){id=10,deptName="主部门2_3",ParentId=2},
            new DepartmentModel(){id=11,deptName="主部门2_4",ParentId=2},
            new DepartmentModel(){id=12,deptName="主部门1_1_1",ParentId=3},
            new DepartmentModel(){id=13,deptName="主部门1_1_2",ParentId=3},
            new DepartmentModel(){id=14,deptName="主部门1_2_1",ParentId=4},
            new DepartmentModel(){id=15,deptName="主部门1_1_1_1",ParentId=12}
            };
            return dplst;
        }

        /// 
        /// 递归生成树形数据
        /// 
        /// 
        /// 
        public List getTrees(int parentid, List nodes)
        {
            List mainNodes = nodes.Where(x => x.ParentId == parentid).ToList();
            List otherNodes = nodes.Where(x => x.ParentId != parentid).ToList();
            foreach (DepartmentModel dpt in mainNodes)
            {
                dpt.Nodes = getTrees(dpt.id,otherNodes);
            }
            return mainNodes;
        }

         
  
    }

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

本人第一次写技术博客 

望各位高手不吝赐教

你可能感兴趣的:(WPF下递归生成树形数据绑定到TreeView上)