3

我有一个包含节点和子节点的 TreeView 列表的程序。这些都启用了复选框属性。我需要知道如何检查检查了哪些节点/节点子节点。到目前为止,我已经能够成功测试父节点,但没有子节点使用:

//this  will turn black any node that is checked, doesn't affect the children though
    TreeNodeCollection nodes = this.treeView1.Nodes;
                foreach (TreeNode n in nodes)
                {
                    if (n.Checked)
                    {
                        n.BackColor = Color.Black;   
                    }
                }

如何让它检查父节点以及子节点?我已经搜索并没有找到任何可以为我解决这个问题的东西。

4

4 回答 4

5

您可以定义一个递归函数来标记所有选定的项目:

private static void MarkSelectedNodes(TreeNodeCollection nodes)
{
    foreach (TreeNode n in nodes)
    {
        if (n.Checked)
            n.BackColor = Color.Black;

        MarkSelectedNodes(n.Nodes);
    }
}

并这样称呼它:

MarkSelectedNodes(treeView1.Nodes);
于 2013-01-25T22:09:26.977 回答
1

您还可以“展开”递归以提高性能并避免堆栈溢出:

private static void MarkSelectedNodes(TreeNodeCollection nodes)
{
    Stack<TreeNode> toProcess =
        new Stack<TreeNode>(nodes.OfType<TreeNode>());

    while (toProcess.Count != 0)
    {
        TreeNode node = toProcess.Pop();
        if (node.Checked)
            node.BackColor = Color.Black;

        foreach (TreeNode child in node.Nodes)
            toProcess.Push(child);
    }
}
于 2013-01-25T22:21:33.867 回答
0

您需要在子节点中再降一层。相同的代码,只是另一个循环:

TreeNodeCollection nodes = this.treeView1.Nodes;
        foreach (TreeNode n in nodes)
        {
            foreach (TreeNode c in n.Nodes)
            {
                if (c.Checked)
                {
                    c.BackColor = Color.Gray;
                }
            }
            if (n.Checked)
            {
                n.BackColor = Color.Black;
            }
        }
于 2013-01-25T22:08:52.740 回答
0
    public static IEnumerable<TreeNode>
                           GetAllCheckedChildNodes(TreeNode node)
    {
        foreach (TreeNode tmpNode in node.Nodes)
        {
            if (tmpNode.Checked)
            {
                yield return tmpNode;
            }

            foreach (var x in GetAllCheckedChildNodes(tmpNode))
            {
                yield return x;
            }
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var checkedNodes = GetAllheckedChildNodes(MyRootNode);
        foreach (TreeNode checkedNode in checkedNodes)
        {
            checkedNode.BackColor = Color.Black;
        }
    }
于 2013-01-25T22:20:55.730 回答