WPF中TreeView控件实现动态加载节点
最近项目需要,使用一个树型控件,其实数据量不大,简单使用一次递归就可以完事,但话说回来,想想,当数据量达到一个量级时,这个方法明显就不足(程序运行十分不给力),而使用节点的深度特性实现加载控制,达到动态生成节点项的目的,这不失为一个好方法。
(全球首款甘特图32年历史) | (完美的用户界面解决方案) |
(报表生成控件) | (慧都独家) |
先来看看本实例的完成图(此处只实现其中动态加载功能,其实后续再补上):
技术点:
数据库结构:
其中Depth为节点深度
核心类TreeViewHelper代码(代码写得没水平请不要见笑,呵呵):
public static void CreatTreeView(TreeView _myTreeView,
myEx_TreeViewItem _parentNode, DataTable dt,
bool isRoot = true, bool isActivity = true, int Depth = 3){ string myFilterString = isRoot? "ParentID = 0":"ParentID = " + _parentNode.ID.ToString();if (isActivity){ #region 动态加载节点if (Depth > 0){ foreach (DataRow row in dt.Select(myFilterString)){ myEx_TreeViewItem item = new myEx_TreeViewItem();item.ID = (int)row["ID"];item.Depth = (int)row["Depth"];item.ItemContent = row["NodeName"].ToString();item.ParentID = (int)row["ParentID"];item.ItemPath = row["NodePath"].ToString();item.IconPath = row["IconPath"].ToString();item.IsExpanded = false;if (isRoot){ _myTreeView.Items.Clear(); //加载根节点前先清除Treeview控件项item.IsExpanded = true;_myTreeView.Items.Add(item); //新增根节点}else{ item.IsExpanded = false;_parentNode.Items.Add(item); //新增下级节点}CreatTreeView(_myTreeView, item, dt,false,true,Depth-1); }}#endregion}else{ #region 递归生成树foreach (DataRow row in dt.Select(myFilterString)){ myEx_TreeViewItem item = new myEx_TreeViewItem();item.ID = (int)row["ID"];item.Depth = (int)row["Depth"];item.ItemContent = row["NodeName"].ToString();item.ParentID = (int)row["ParentID"];item.ItemPath = row["NodePath"].ToString();item.IconPath = row["IconPath"].ToString();if (isRoot){ _myTreeView.Items.Clear();item.IsExpanded = true;_myTreeView.Items.Add(item); //新增根节点}else{ item.IsExpanded = false;_parentNode.Items.Add(item); //新增下级节点}CreatTreeView(_myTreeView, item, dt, false);}#endregion}}public static void CreatTreeViewItemChild(TreeView _myTreeView, myEx_TreeViewItem _SelectedParentItem, DataTable dt, int Depth = 2){ _SelectedParentItem.Items.Clear();if (Depth > 0) //判断加载的深度,默认只加载两级{ //设定过滤条件string myFilterString;myFilterString = "ParentID = " + _SelectedParentItem.ID.ToString();foreach (DataRow row in dt.Select(myFilterString)){ myEx_TreeViewItem item = new myEx_TreeViewItem();item.ID = (int)row["ID"];item.Depth = (int)row["Depth"];item.ItemContent = row["NodeName"].ToString();item.ParentID = (int)row["ParentID"];item.ItemPath = row["NodePath"].ToString();item.IconPath = row["IconPath"].ToString();item.IsExpanded = false;_SelectedParentItem.Items.Add(item); //新增下级节点CreatTreeViewItemChild(_myTreeView, item, dt, (Depth - 1));}}}有不足之处请指点,代码整理后再分享给大下,以下是程序的Demo,可看看实际效果,需要net4.0版本运行环境