实现C# TreeView的AfterCheck事件中的Checked,主要有以下情况:
1.父节点勾选则子节点全部勾选
2.父节点不勾选则子节点全部不勾选
3.子节点全部不勾选则父节点不勾选
4.子节点部分勾选则父节点不勾选
5.子节点全部勾选则父节点被勾选
以下是递归实现
private void SetNodeCheckStatus(TreeNode tn, bool chk)
{
if (tn == null)
return;
// Set child nodes check status
foreach( TreeNode tnChild in tn.Nodes)
{
tnChild.Checked = chk;
SetNodeCheckStatus(tnChild, chk);
}
// Set parent check status
int nNodeCount = 0;
TreeNode tnParent = tn;
while(tnParent.Parent != null)
{
nNodeCount = 0;
tnParent = tnParent.Parent;
foreach(TreeNode tnTmp in tnParent.Nodes)
{
if (tnTmp.Checked == chk)
{
nNodeCount++;
}
}
if (nNodeCount == tnParent.Nodes.Count)
tnParent.Checked = chk;
else
tnParent.Checked = false;
}
}