WPF TreeView 展开到指定节点
Posted wuyaxiansheng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF TreeView 展开到指定节点相关的知识,希望对你有一定的参考价值。
最近在做一个交换机管理的项目,有一个交换机的树,做树的搜索的时候 展开节点居然有点难,自己记录下来 ,以后用的到的时候可以看一下。
展开代码如下,其中
SwitchTree是treeview空间的名称,TreeNode 是绑定在树上的数据类的名称,请注意
private void ExpendTree(TreeNode node) SwitchTree.UpdateLayout(); for (int i = 0; i < SwitchTree.Items.Count; i++) TreeNode findNd = SwitchTree.Items[i] as TreeNode; TreeViewItem ti = SwitchTree.ItemContainerGenerator.ContainerFromIndex(i) as TreeViewItem; if (findNd == node && ti != null) ti.IsExpanded = true; ti.IsSelected = true; if (ti.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated) ti.UpdateLayout(); //展开 EependTreeByNode(ti); break; else if (ti != null) TreeViewItem treeViewItem= RecurFindeNode(node, ti); if (treeViewItem == null) ti.IsExpanded = false; continue; //展开 EependTreeByNode(treeViewItem); break; //EependTreeByNode(node); private TreeViewItem RecurFindeNode(TreeNode n, TreeViewItem items) TreeViewItem tv = null; if (n != null && items != null && items.HasItems) items.IsExpanded = true; foreach (var item in items.Items) var node = item as TreeNode; if (node == null || (node.nodes!=null&&!node.nodes.Any())) continue; if (items.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated) items.UpdateLayout(); TreeViewItem m_item = items.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem; if (n == node && m_item != null) //EependTreeByNode(m_item); tv = m_item; else TreeViewItem treeNode = RecurFindeNode(n, m_item); if (treeNode != null) tv = treeNode; break; else //items.IsExpanded = false; return tv; private void EependTreeByNode(TreeViewItem contenier) if (contenier != null) //if (contenier.HasItems) // contenier.IsExpanded = true; contenier.IsSelected = true; // //else // // TreeViewItem parent = (TreeViewItem)contenier.Parent; // if (parent != null) // // parent.IsExpanded = true; // parent.IsSelected = true; // // if (contenier.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated) contenier.UpdateLayout();
以上是关于WPF TreeView 展开到指定节点的主要内容,如果未能解决你的问题,请参考以下文章
求:WPF中TreeView如何实现展开一个节点其他节点关闭!
WPF TreeView通过绑定方式,节点下有1000个以上节点(业务需要几千个),展开会卡死,求解或者其他实现方式