如何选中或取消选中 TreeView 中的所有子节点 [英] How to Check or Uncheck All Child Nodes in TreeView

查看:25
本文介绍了如何选中或取消选中 TreeView 中的所有子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Deselect button in my application, but its not working well. If I am going to deselect the folder it will deselect. But the folder within a subfolder will remain selected(checked).

对这个问题的任何帮助将不胜感激.

Any help with this issue would be appreciated.

推荐答案

你应该找到所有节点,包括后代,然后设置Checked=false.

例如你可以使用这个扩展方法来获取树的所有后代节点或一个节点的后代:

For example you can use this extension method to get all descendant nodes of tree or descendants of a node:

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();
    }
}

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

Then you can use above methods on tree or a node to uncheck all descendant nodes of tree or uncheck all descendant nodes of a node:

取消选中树的后代节点:

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;

这篇关于如何选中或取消选中 TreeView 中的所有子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆