如何在TreeView控件中选择所有父节点(最多为根节点)? [英] How to get all parents (up to root) nodes for selected in TreeView control?
问题描述
如果我有一个TreeView(myTreeview),如何获取所选节点的所有父节点(父节点,父母的父节点等)的列表?
If I have a TreeView (myTreeview),how can I obtain a list of all parent nodes (parent, parents of parents ect.) of selected node?
推荐答案
我建议您创建一组自己的树助手,例如,下一个针对您的问题:
I'd recomended you to create a set of your own tree helpers, for example, next one is for your problem:
public static class TreeHelpers
{
public static IEnumerable<TItem> GetAncestors<TItem>(TItem item, Func<TItem, TItem> getParentFunc)
{
if (getParentFunc == null)
{
throw new ArgumentNullException("getParentFunc");
}
if (ReferenceEquals(item, null)) yield break;
for (TItem curItem = getParentFunc(item); !ReferenceEquals(curItem, null); curItem = getParentFunc(curItem))
{
yield return curItem;
}
}
//TODO: Add other methods, for example for 'prefix' children recurence enumeration
}
用法示例(在您的情况下):
And example of usage (in your context):
IList<TreeNode> ancestorList = TreeHelpers.GetAncestors(node, x => x.Parent).ToList();
为什么这比使用list<>.Add()更好? -因为我们可以使用惰性LINQ函数,例如.FirstOrDefault(x => ...)
Why is this better than using list<>.Add()? - because we can use lazy LINQ functions, such as .FirstOrDefault(x => ...)
P.S.要将当前"项包含到可枚举的结果中,请使用TItem curItem = item
而不是TItem curItem = getParentFunc(item)
P.S. to include 'current' item into result enumerable, use TItem curItem = item
, instead of TItem curItem = getParentFunc(item)
这篇关于如何在TreeView控件中选择所有父节点(最多为根节点)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!