在 TreeView 中搜索 TreeNodes

Search TreeNodes in a TreeView

我有一个 TreeView 包含一些 TreeNode,如下所示:

我的想法是使用 textBox1 作为搜索引擎,只显示包含 textBox1 文本的树节点。 我已经有一个函数可以解析不同的节点并查看 textBox1 中包含的文本是否包含在每个节点中:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    foreach (var node in Collect(treeView1.Nodes))
    {
        if (node.Text.ToLower().Contains(textBox1.Text.ToLower()))
        {
            //I want to show those nodes 
            Debug.Write("Contained : ");
            Debug.WriteLine(node.Text);
        }
        else
        {
            //I want to hide those nodes
            Debug.Write("Not contained : ");
            Debug.WriteLine(node.Text);
        }
    }
}

TreeNode的属性isVisible只有一个getter,如何隐藏不包含搜索文本的TreeNode?

从文档来看,没有办法隐藏树节点。但是您可以删除并重新添加该节点。 您可以使用以下方法执行此操作:

public class RootNode : TreeNode
{
    public List<ChildNode> ChildNodes { get; set; }

    public RootNode()
    {
        ChildNodes = new List<ChildNode>();
    }

    public void PopulateChildren()
    {
        this.Nodes.Clear();

        var visibleNodes = 
            ChildNodes
            .Where(x => x.Visible)
            .ToArray();

        this.Nodes.AddRange(visibleNodes);
    }

    //you would use this instead of (Nodes.Add)
    public void AddNode(ChildNode node)
    {
        if (!ChildNodes.Contains(node))
        {
            node.ParentNode = this;
            ChildNodes.Add(node);
            PopulateChildren();
        }
    }

    //you would use this instead of (Nodes.Remove)
    public void RemoveNode(ChildNode node)
    {
        if (ChildNodes.Contains(node))
        {
            node.ParentNode = null;
            ChildNodes.Remove(node);
            PopulateChildren();
        }

    }
}

public class ChildNode : TreeNode
{
    public RootNode ParentNode { get; set; }
    private bool visible;
    public bool Visible { get { return visible; } set { visible = value;OnVisibleChanged(): } }
    private void OnVisibleChanged()
    {
        if (ParentNode != null)
        {
            ParentNode.PopulateChildren();
        }
    }
}