WPF TreeView 展开到指定节点
2021-05-23 18:30
标签:tree view void 空间 管理 class 一个 oid vat 最近在做一个交换机管理的项目,有一个交换机的树,做树的搜索的时候 展开节点居然有点难,自己记录下来 ,以后用的到的时候可以看一下。 展开代码如下,其中 WPF TreeView 展开到指定节点 标签:tree view void 空间 管理 class 一个 oid vat 原文地址:https://www.cnblogs.com/wuyaxiansheng/p/11130939.htmlSwitchTree是treeview空间的名称,TreeNode 是绑定在树上的数据类的名称,请注意
private void ExpendTree(TreeNode node)
{
SwitchTree.UpdateLayout();
for (int i = 0; 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();
}
}
}