循环遍历所有树视图项 [英] Loop through all treeview items recursive
问题描述
我需要一个循环遍历所有TreeViewItems的函数,并为Beak提供具有特定标题的TreeViewItem ...
例如:
$ / $
I need a function which loops through all TreeViewItems and give beak the TreeViewItem which got a specific Header...
For example:
GetSearchedTreeViewItemByHeader(string _header)
{
var searchedNode = new TreeViewItem();
foreach(var node in treeView.Items)
{
if(node.Header == _header)
{
searchedNode = node
}
}
return searchedNode
}
这仅适用于第一项treeView,有谁知道我如何遍历所有项目(也是所有的子项目......)?我不知道我只是从递归解决方案中听到但我不知道怎么做...
提前感谢!
编辑:
我使用WPF
我尝试过:
TreeViewItems.Items检查,for循环,while循环
this only works for the first Item in the treeView, does anybody know how i loop through all items(also all childitems...)? i got no idea i only heard from a recursive solution but i dont know how to do it...
thanks in advance!
I use WPF
What I have tried:
TreeViewItems.Items check, for loop, while loop
推荐答案
该任务的递归如此常见甚至微软已发布一个recursice代码片段。
提示:如果搜索特定项目,则将其用作附加输入参数。
The recursion on that task is so common that even Microsoft has published a recursice code snippet.
tip: if you search a specific item, you use it as additional input parameter.
这是迭代任何层次结构中所有节点的通用扩展方法:
Here's a generic extension method to iterate all nodes in any hierarchy:
private static IEnumerable<T> SelectRecursiveIterator<T>(IEnumerable<T> source, Func<T, IEnumerable<T>> getChildren)
{
var stack = new Stack<IEnumerator<T>>();
try
{
stack.Push(source.GetEnumerator());
while (stack.Count != 0)
{
IEnumerator<T> iter = stack.Peek();
if (iter.MoveNext())
{
T current = iter.Current;
yield return current;
IEnumerable<T> children = getChildren(current);
if (children != null) stack.Push(children.GetEnumerator());
}
else
{
iter.Dispose();
stack.Pop();
}
}
}
finally
{
while (stack.Count != 0)
{
stack.Pop().Dispose();
}
}
}
public static IEnumerable<T> SelectRecursive<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> getChildren)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (getChildren == null) return source;
return SelectRecursiveIterator(source, getChildren);
}
有了这个,您可以迭代树中的所有节点,并返回所有匹配的节点:
With that in place, you can iterate all the nodes in your tree, and return either all matching nodes:
static IEnumerable<TreeNode> FindAllNodesByHeader(TreeView tree, string header)
{
return tree.Items.Cast<TreeViewItem>().SelectRecursive(node => node.Items.Cast<TreeViewItem>()).Where(node => node.Header == header);
}
或只是第一个匹配的节点:
or just the first matching node:
static TreeNode FindFirstNodeByHeader(TreeView tree, string header)
{
return tree.Items.Cast<TreeViewItem>().SelectRecursive(node => node.Items.Cast<TreeViewItem>()).FirstOrDefault(node => node.Header == header);
}
这篇关于循环遍历所有树视图项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!