winform Treeview Checkbox选择事件



   private void treeView1_MouseClick( object sender, MouseEventArgs e)
{
TreeNode node
= treeView1.GetNodeAt( new Point(e.X, e.Y));
if (node != null )
{
ChangeChild(node, node.Checked);
// 影响子节点
ChangeParent(node); // 影响父节点
}
}

// 递归子节点跟随其全选或全不选
private void ChangeChild(TreeNode node, bool state)
{
node.Checked
= state;
foreach (TreeNode tn in node.Nodes)
ChangeChild(tn, state);
}

// 递归父节点跟随其全选或全不选
private void ChangeParent(TreeNode node)
{
if (node.Parent != null )
{
// 兄弟节点被选中的个数
int brotherNodeCheckedCount = 0 ;
// 遍历该节点的兄弟节点
foreach (TreeNode tn in node.Parent.Nodes)
{
if (tn.Checked == true )
brotherNodeCheckedCount
++ ;
}
// 兄弟节点全没选,其父节点也不选
if (brotherNodeCheckedCount == 0 )
{
node.Parent.Checked
= false ;
ChangeParent(node.Parent);
}
// 兄弟节点只要有一个被选,其父节点也被选
if (brotherNodeCheckedCount >= 1 )
{
node.Parent.Checked
= true ;
ChangeParent(node.Parent);
}
}
}
   private void treeView1_MouseClick( object sender, MouseEventArgs e)
{
TreeNode node
= treeView1.GetNodeAt( new Point(e.X, e.Y));
if (node != null )
{
ChangeChild(node, node.Checked);
// 影响子节点
ChangeParent(node); // 影响父节点
}
}

// 递归子节点跟随其全选或全不选
private void ChangeChild(TreeNode node, bool state)
{
node.Checked
= state;
foreach (TreeNode tn in node.Nodes)
ChangeChild(tn, state);
}

// 递归父节点跟随其全选或全不选
private void ChangeParent(TreeNode node)
{
if (node.Parent != null )
{
// 兄弟节点被选中的个数
int brotherNodeCheckedCount = 0 ;
// 遍历该节点的兄弟节点
foreach (TreeNode tn in node.Parent.Nodes)
{
if (tn.Checked == true )
brotherNodeCheckedCount
++ ;
}
// 兄弟节点全没选,其父节点也不选
if (brotherNodeCheckedCount == 0 )
{
node.Parent.Checked
= false ;
ChangeParent(node.Parent);
}
// 兄弟节点只要有一个被选,其父节点也被选
if (brotherNodeCheckedCount >= 1 )
{
node.Parent.Checked
= true ;
ChangeParent(node.Parent);
}
}
}

你可能感兴趣的:(winform Treeview Checkbox选择事件)