如果取消选中父节点,如何取消选中子节点?

时间:2013-08-20 12:57:29

标签: c# winforms

如果取消选中父节点,我想取消选中子节点。如果检查子节点父节点被选中,则根据我的代码。这是写方式,但是当我取消选中时,父节点子节点仍保持检查状态。我在AfterCheck活动中完成了以下代码。

private bool updatingTreeView;
        private void treSelector_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if (updatingTreeView) return;
            updatingTreeView = true;
            SelectParents(e.Node, e.Node.Checked);
            updatingTreeView = false;
        }

private void SelectParents(TreeNode node, Boolean isChecked)
        {
            var parent = node.Parent;

            if (parent == null)
            {
                //CheckAllChildren(treSelector.Nodes, false);
                return;
            }

            if (isChecked)
            {
                parent.Checked = true; // we should always check parent
                SelectParents(parent, true);
            }
            else
            {
                if (parent.Nodes.Cast<TreeNode>().Any(n => n.Checked))
                    return; // do not uncheck parent if there other checked nodes

                SelectParents(parent, false);
            }
        }

如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

我认为你可以写另一种方法:

void checkChildNodes(TreeNode theNode, bool isChecked)
{
    if (theNode == null) return;
    theNode.Checked = isChecked;
    foreach(TreeNode childNode in theNode.Nodes)
    {
        checkChildNodes(childNode, isChecked);
    }
}

答案 1 :(得分:0)

我在updatingtreeview=false

之前的aftercheck事件中添加了以下代码
 if (e.Node.Checked==false)
            {
                if (e.Node.Nodes.Count > 0)
                {
                    /* Calls the CheckAllChildNodes method, passing in the current 
                    Checked value of the TreeNode whose checked state changed. */
                    this.CheckAllChildNodes(e.Node, e.Node.Checked);
                }
            }

和方法是

private void CheckAllChildNodes(TreeNode treeNode, bool nodeChecked)
        {
            foreach (TreeNode node in treeNode.Nodes)
            {
                node.Checked = nodeChecked;
                if (node.Nodes.Count > 0)
                {
                    // If the current node has child nodes, call the CheckAllChildsNodes method recursively. 
                    this.CheckAllChildNodes(node, nodeChecked);
                }
            }
        }

工作正常..