如何选中或取消选中 TreeView 中的所有子节点

San*_*nur 1 c# treeview tree winforms

我的应用程序中有一个“取消选择”按钮,但效果不佳。如果我要取消选择该文件夹,它将取消选择。但子文件夹中的文件夹将保持选中状态(选中)。

任何有关此问题的帮助将不胜感激。

在此输入图像描述

Rez*_*aei 5

您应该找到包括后代在内的所有节点,然后设置Checked=false

例如,您可以使用此扩展方法来获取树的所有后代节点或节点的后代:

using System.Linq;
using System.Windows.Forms;
using System.Collections.Generic;

public static class Extensions
{
    public static List<TreeNode> Descendants(this TreeView tree)
    {
        var nodes = tree.Nodes.Cast<TreeNode>();
        return nodes.SelectMany(x => x.Descendants()).Concat(nodes).ToList();
    }

    public static List<TreeNode> Descendants(this TreeNode node)
    {
        var nodes = node.Nodes.Cast<TreeNode>().ToList();
        return nodes.SelectMany(x => Descendants(x)).Concat(nodes).ToList();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以在树或节点上使用上述方法来取消选中树的所有后代节点或取消选中节点的所有后代节点:

取消选中树的后代节点:

this.treeView1.Descendants().Where(x => x.Checked).ToList()
              .ForEach(x => { x.Checked = false; });
Run Code Online (Sandbox Code Playgroud)

取消选中节点的后代节点:

例如对于节点 0:

this.treeView1.Nodes[0].Descendants().Where(x => x.Checked).ToList()
              .ForEach(x => { x.Checked = false; });
Run Code Online (Sandbox Code Playgroud)

不要忘记添加using System.Linq;