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

标签 c# winforms tree treeview

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

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

enter image description here

最佳答案

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

关于c# - 如何选中或取消选中 TreeView 中的所有子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34921308/

相关文章:

c# - 找到树的最大深度

c# - 使用 Server.Transfer() 返回时出错

c# - 在.NET Core 3.1中关闭C#套接字的正确方法是什么?

c# - WPF 请稍候对话框

c# - 使用 for 循环将自定义对象分配给数组?

vb.net - 如何制作复合用户控件 VB.NET

algorithm - 二维空间中的最短路径和排序点

java - Java或C++中的递归广度优先旅行函数?

C#:用XmlDocument解析XML时的行信息

c# - 在 C# 中显示密码文本框的纯文本