C# window forms Treeview checkbox子节点和父节点相互选中的关系
//全局变量
private bool m_SetClick = true;
//树的AfterCheck事件
private void recievedPeopletreeView_AfterCheck(object sender, TreeViewEventArgs e)
{
if (m_SetClick)
{
SetSubNodeCheck(e.Node, e.Node.Checked);
SetParentCheck(e.Node);
SetParentNotCheck(e.Node);
m_SetClick = true;
}
}
private void SetSubNodeCheck(TreeNode p_TreeNode,bool p_SelectCheck)
{
m_SetClick = false;
foreach (TreeNode _SubNode in p_TreeNode.Nodes)
{
_SubNode.Checked = p_SelectCheck;
SetSubNodeCheck(_SubNode, p_SelectCheck);
}
}
private void SetParentCheck(TreeNode p_TreeNode)
{
if (p_TreeNode.Checked && p_TreeNode.Parent != null)
{
p_TreeNode.Parent.Checked = true;
SetParentCheck(p_TreeNode.Parent);
}
}
private void SetParentNotCheck(TreeNode p_TreeNode)
{
if (!p_TreeNode.Checked && p_TreeNode.Parent != null)
{
foreach (TreeNode _Node in p_TreeNode.Parent.Nodes)
{
if (_Node.Checked) return;
}
p_TreeNode.Parent.Checked = false;
SetParentNotCheck(p_TreeNode.Parent);
}
}