簡體   English   中英

如何在TreeView控件中選擇所有父節點(最多根節點)?

[英]How to get all parents (up to root) nodes for selected in TreeView control?

如果我有一個TreeView(myTreeview),我如何獲得所選節點的所有父節點(父節點,父節點的父節點等)的列表?

我建議你創建一組自己的樹幫助器,例如,下一個是你的問題所在:

    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
    }

使用示例(在您的上下文中):

        IList<TreeNode> ancestorList = TreeHelpers.GetAncestors(node, x => x.Parent).ToList();

為什么這比使用list <>更好。添加()? - 因為我們可以使用惰性LINQ函數,例如.FirstOrDefault(x => ...)

PS將'當前'項包含到結果可枚舉中,使用TItem curItem = item ,而不是TItem curItem = getParentFunc(item)

如果需要實際對象,請遞歸使用TreeNode.Parent屬性,直到到達根目錄。 就像是:

private void GetPathToRoot(TreeNode node, List<TreeNode> path)
{
    if(node == null) return; // previous node was the root.
    else
    {
        path.add(node);
        GetPathToRoot(node.Parent, path);
    }
}

Alexander Mavrinsky的回答非常有用,但我的方法有很多變化。 我的代碼不僅在方法中更短,更清晰,而且在調用站點中(通過指定他的泛型)。

public static class TreeExtensions
{
    public static IEnumerable<TreeNode> GetAncestors(this TreeNode node)
    {
        if (node == null)
            yield break;
        while ((node = node.Parent) != null)
            yield return node;
    }
}

例如: var firstCheckedAncestor = treeNode.GetAncestors().First(x => x.Checked);

或者,如果您確實需要每個父節點: var allAncestors = treeNode.GetAncestors().ToList();


但是如果你計划使用相同的邏輯有多個類,這里​​是通用方法和每個類的幾個擴展(這樣你就可以在每個調用者上保持更簡單的API):

public static IEnumerable<T> GetAncestors<T>(T item, Func<T, T> getParent)
{
    if (item == null)
        yield break;
    while ((item = getParent(item)) != null)
        yield return item;
}
public static IEnumerable<TreeNode> GetAncestors(this TreeNode node) => GetAncestors(node, x => x.Parent);
public static IEnumerable<Control> GetAncestors(this Control control) => GetAncestors(control, x => x.Parent);

我認為你需要一個節點數組

List<TreeNode> resultNodes = new List<TreeNode>()
private void GetNodesToRoot(TreeNode node)
{
    if(node == null) return; // previous node was the root.
    else
    {
        resultNodes.add(node);
        GetNodesToRoot(node.Parent);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM