问题描述
我有一个包含许多项目的树状视图
I have a treeview with many items
当我展开一个项目及其子项并调用 refresh 方法后,展开的项子项会折叠起来.
When I expand an item and its childs and after I called refresh method, that expanded item childs becomes collapsed.
你能告诉我如何存储所选节点并在刷新后再次调用 Expand 方法...
Can you give me an idea how to store the selected node and after refresh, to call the Expand method again...
我试过了:
TreeNode selectedNode = new TreeNode();
TreeNode selectedNode = SelectedTreeNode(); //method which takes selected node from TV
RestoreFolderTreeWithLastSelectedItem(); //method which initialise treeview object
//here I want to call Expand() method but it not exists to TreeNode.
对于 treeview,我使用了 Windows.Controls.treeView
命名空间我是初学者...谢谢
For treeview, I used Windows.Controls.treeView
namespaceI am beginner...Thank you
我会用图片来解释
我展开了所有项目:
如果我按 F5 或调用 Refresh 函数 (RestoreFolderTreeWithLastSelectedItem();) 那么它们将像这样折叠:
If I press F5 or call Refresh function (RestoreFolderTreeWithLastSelectedItem();) then they will be collapsed like as:
而不是第一张图片...
instead of first image...
推荐答案
我将它与 WinForms TreeView 一起使用.它保存刷新之间的节点展开状态:
I'm using this with a WinForms TreeView. It saves the nodes expanded state between refreshes:
// Save the path of the expanded tree branches
var savedExpansionState = treeView1.Nodes.GetExpansionState();
treeView1.BeginUpdate();
// TreeView is populated
// ...
// Once it is populated, we need to restore expanded nodes
treeView1.Nodes.SetExpansionState(savedExpansionState);
treeView1.EndUpdate();
这是实现此目的的代码:
Here is the code to achieve this:
public static class TreeViewExtensions
{
public static List<string> GetExpansionState(this TreeNodeCollection nodes)
{
return nodes.Descendants()
.Where(n => n.IsExpanded)
.Select(n => n.FullPath)
.ToList();
}
public static void SetExpansionState(this TreeNodeCollection nodes, List<string> savedExpansionState)
{
foreach (var node in nodes.Descendants()
.Where(n => savedExpansionState.Contains(n.FullPath)))
{
node.Expand();
}
}
public static IEnumerable<TreeNode> Descendants(this TreeNodeCollection c)
{
foreach (var node in c.OfType<TreeNode>())
{
yield return node;
foreach (var child in node.Nodes.Descendants())
{
yield return child;
}
}
}
}
这篇关于在 C# 中刷新 TreeView 后展开选定的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!