-1

如果父节点未选中,我想取消选中子节点。根据我的代码,如果我检查了子节点父节点被选中。这是写入方式,但是当我取消选中父节点时,子节点仍然处于选中状态。我在 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);
            }
        }

如何解决这个问题?

4

2 回答 2

1

我认为您可以编写另一种方法,如下所示:

void checkChildNodes(TreeNode theNode, bool isChecked)
{
    if (theNode == null) return;
    theNode.Checked = isChecked;
    foreach(TreeNode childNode in theNode.Nodes)
    {
        checkChildNodes(childNode, isChecked);
    }
}
于 2013-08-20T13:05:14.023 回答
0

我之前在 aftercheck 事件中添加了以下代码updatingtreeview=false

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

它工作正常..

于 2013-08-22T14:07:48.960 回答