【发布时间】:2011-03-11 14:31:49
【问题描述】:
以下代码直接取自微软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);
}
}
}
你把它放在一个包含树视图的表单中,然后在树视图 AfterCheck 事件上调用 node_AfterCheck(惊喜,惊喜)。然后它递归地检查或取消选中树视图上的子节点。
但是,如果您真的尝试过,并且足够快地在同一个树视图复选框上单击几次,子节点最终会与父节点不同步。您可能需要几个级别的子级,总共可能有 100 个子级,以便 UI 更新足够慢以注意到这种情况。
我已经尝试了几件事(例如在 node_AfterCheck 开始时禁用树视图控件并在结束时重新启用),但仍然会出现不同步问题。
有什么想法吗?
【问题讨论】:
-
我已将我的解决方法发布到此主题的子主题中:stackoverflow.com/questions/14699102/…
标签: winforms treeview checkbox