以下代码直接来自于Microsoft,网址为 http://msdn.microsoft.com/en-us/library/system.windows.forms.treeview.aftercheck%28VS.80%29.aspx。
// Updates all child tree nodes recursively.
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);
}
}
}
// NOTE This code can be added to the BeforeCheck event handler instead of the AfterCheck event.
// After a tree node's Checked property is changed, all its child nodes are updated to the same value.
private void node_AfterCheck(object sender, TreeViewEventArgs e)
{
// The code only executes if the user caused the checked state to change.
if (e.Action != TreeViewAction.Unknown)
{
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);
}
}
}
在一个包含树形视图的表单中,您调用了treeview的AfterCheck事件上的node_AfterCheck函数。然后,它递归地检查或取消选中treeview上的子节点。
但是,如果您实际尝试并快速多次单击同一棵树的复选框,则子节点最终会导致其选中状态与父节点不同步。您可能需要几层子级,其中每个子级可能包含100个子项,以使UI更新足够缓慢,才能注意到此问题。
我已经尝试过一些方法(例如,在node_AfterCheck开头禁用treeview控件,并在结束时重新启用),但是不同步的问题仍然发生。
有任何想法吗?