C#TreeView上下級Checked屬性關聯處理
private void TreeNodeChild(TreeNode ATreeNode, bool AChecked) // 同步子节点
{
if (ATreeNode == null) return;
ATreeNode.Checked = AChecked;
foreach (TreeNode vTreeNode in ATreeNode.Nodes)
TreeNodeChild(vTreeNode, AChecked);
}
private void TreeNodeCheck(TreeNode ATreeNode, bool AChecked)
{
if (ATreeNode == null) return;
ATreeNode.Checked = AChecked;
if (AChecked) // 如果选中本节点这就是选中全部上级节点
{
TreeNodeCheck(ATreeNode.Parent, AChecked);
}
else
{
if (ATreeNode.Parent != null && ATreeNode.Parent.Checked)
{
foreach(TreeNode vTreeNode in ATreeNode.Parent.Nodes)
if (vTreeNode.Checked) return;
TreeNodeCheck(ATreeNode.Parent, AChecked); // 判断是否所有的兄弟节点Checked都为false
}
}
}
private bool updateTreeNode= false;
private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
if (updateTreeNode) return; // 如果在刷新中
updateTreeNode = true;
try
{
TreeNodeChild(e.Node, e.Node.Checked); // 同步子节点
TreeNodeCheck(e.Node, e.Node.Checked);
}
finally
{
updateTreeNode = false;
}
}