开发者

What algorithm is used in this code?

开发者 https://www.devze.com 2023-02-09 08:59 出处:网络
This code checks and unchecks the child nodes of a treeview control. What algorithm is used in this code?

This code checks and unchecks the child nodes of a treeview control. What algorithm is used in this code?

private int _callCountUp;

pr开发者_Python百科ivate int _callCountDn;

private void tvwPermissions_AfterCheck(object sender, System.Windows.Forms.TreeViewEventArgs e)
        {
            bool anyChecked = false;

            if (_callCountDn == 0 && e.Node.Parent != null)
            {
                anyChecked = false;
                foreach (TreeNode childNode in e.Node.Parent.Nodes)
                {
                    if (childNode.Checked)
                    {
                        anyChecked = true;
                        break;
                    }
                }
                _callCountUp += 1;

                if (anyChecked)
                    e.Node.Parent.Checked = true;

                _callCountUp -= 1;
            }

            if (_callCountUp == 0)
            {
                foreach (TreeNode childNode in e.Node.Nodes)
                {
                    _callCountDn += 1;
                    childNode.Checked = e.Node.Checked;
                    _callCountDn -= 1;
                }
            }
        }


Not so sure this has a name. It is quite standard, the _callCountUp/Dn fields avoid trouble when changing the Checked property of a node causes the AfterCheck event handler to run again. StackOverflow is a very typical outcome when the event handler recurses without bound.

The generic pattern resembles this:

private bool modifyingNodes;

private void treeview_AfterCheck(object sender, TreeViewEventArgs e) {
    if (modifyingNodes) return;
    modifyingNodes = true;
    try {
       // etc..
    }
    finally {
       modifyingNodes = false;
    }
}

The finally block ensures that a handled exception (such as through ThreadExceptionDialog) doesn't permanently leave the state variable set to true. It's optional of course.

0

精彩评论

暂无评论...
验证码 换一张
取 消