WPF|WPF Treeview 无限分级绑定集合数据
WPF Treeview 无限分级绑定集合数据
2013-04-28 16:42 by swarb, ... 阅读, ... 评论, 收藏, 编辑 【WPF|WPF Treeview 无限分级绑定集合数据】
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mode="clr-namespace:WpfTreeviewDemo"
Title="TreeView无限级树绑定事例" Height="300" Width="300" WindowStartupLocation="CenterScreen" DataContext="{Binding}" ResizeMode="CanMinimize">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Diagnostics;
using System.Windows.Markup;
namespace WpfTreeviewDemo
{
//定义节点类Node
public class Node
{
//构造函数
public Node()
{
this.Nodes = new List
}
public int ID { get;
set;
}//内码
public string Name { get;
set;
}//名称
public bool IsParent { get;
set;
}//是否父级
public int OwnerID { get;
set;
}//上一级内码
public List
}
///
/// MainWindow.xaml 的交互逻辑
///
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List
{
new Node { ID = 1000, Name = "系统", IsParent=true,OwnerID = 0},
new Node { ID = 1100, Name = "软件设置", IsParent=false, OwnerID = 1000 },
new Node { ID = 1200, Name = "数据备份", IsParent=false, OwnerID = 1000 },
new Node { ID = 1300, Name = "数据恢复", IsParent=false, OwnerID = 1000 },
new Node { ID = 2000, Name = "基础资料", IsParent=true,OwnerID = 0},
new Node { ID = 2100, Name = "用户管理", IsParent=false, OwnerID = 2000 },
new Node { ID = 2200, Name = "用户组", IsParent=false, OwnerID = 2000 },
new Node { ID = 2300, Name = "组织机构", IsParent=false, OwnerID = 2000 },
};
List
this.TreeView.ItemsSource = outputList;
//绑定TreeView.Items数据源
}
///
/// 绑定树
///
List
{
List
for (int i = 0;
i < nodes.Count;
i++)//按节点数量循环
{
if (nodes[i].OwnerID == 0)//判断是否根节点
{
outputList.Add(nodes[i]);
//是根节点的,节点集合中加上节点
}
else
{
FindDownward(nodes, nodes[i].OwnerID).Nodes.Add(nodes[i]);
//不是根节点的向下查找
}
}
return outputList;
}
///
/// 向下查找
///
Node FindDownward(List
{
if (nodes == null)
{
return null;
//节点集合为空返回null
}
for (int i = 0;
i < nodes.Count;
i++)//按nodes节点集合数量循环
{
if (nodes[i].ID == id)//判断节点的id是否与父节点相同
{
return nodes[i];
//是父节点返回节点
}
Node node = FindDownward(nodes[i].Nodes, id);
//向下查找
if (node != null)//节点不等于返回节点
{
return node;
}
}
return null;
//返回空值
}
}
}
推荐阅读
- 07/22【晨读感悟】保持好奇心,生活才有无限可能
- 星际无限|星际无限 | 官方推出Filecoin MinerX奖学金计划,吸引中小型Filecoin矿工
- 生活不就是这样吗(一边努力着一边辛苦着,想到为的人还无限幸福着)
- 致无限美好的2019
- 鹊桥仙|鹊桥仙 诗思无限
- 坎
- 只想
- WPF使用代码创建数据模板DataTemplate
- 追求人类的无限可能性
- 无限风光在险峰