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

How to Check or Uncheck All Child Nodes in TreeView

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

如能就此问题提供任何帮助,我们将不胜感激。

您应该找到包括后代在内的所有节点,然后设置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();
    }
}

那么你可以在树或节点上使用上面的方法来取消选中树的所有后代节点或取消选中节点的所有后代节点:

取消选中树的后代节点:

this.treeView1.Descendants().Where(x => x.Checked).ToList()
              .ForEach(x => { x.Checked = false; });

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

例如节点 0:

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

别忘了加上using System.Linq;