C# TreeView组件TreeNode节点自动勾选解决方案(TreeViewNodeCheckHander)
作者:C/S框架网|www.cscode.ne  发布日期:2021-06-01 11:12:10
  C# TreeView组件TreeNode节点自动勾选解决方案(TreeViewNodeCheckHander)



TreeView 节点自动勾选的场景:

1. 勾选/不勾选父级节点,要同步更新所有子节点的状态
2. 当勾选子节点,父节点必须勾选!
3. 当所有子节点全部勾选,父节点必须是勾选状态
4. 当所有子节点全部不勾选,父节点必须是不勾选状态



C# TreeView组件TreeNode节点自动勾选解决方案(TreeViewNodeCheckHander)



TreeViewNodeCheckHander类使用方法



C# Code:

private void frmSoftwareFunction_Load(object sender, EventArgs e)
{
  
  tv.Nodes.Clear();
  TreeViewNodeCheckHander.Handle(tv);
}


//来源:C/S框架网 | www.csframework.com | QQ:23404761




TreeViewNodeCheckHander类:



C# Code:


/// <summary>
/// TreeView组件TreeNode节点自动勾选几种场景及解决方案
/// </summary>
public class TreeViewNodeCheckHander
{
  
public static void Handle(TreeView tv)
  {
    tv.AfterCheck +
= OnTreeView_AfterCheck;
  }
  
  
private static void OnTreeView_AfterCheck(object sender, TreeViewEventArgs e)
  {
    
//若当前节点包含子节点,勾选或不勾选全部子节点
    
if (e.Node.Nodes.Count > 0)
    {
      SetCheck(e.Node.Nodes, e.Node.Checked);
      
return;
    }
    
    
//当前节点已勾选,父级节点也要勾选
    
if (e.Node.Checked && e.Node.Parent != null && e.Node.Parent.Checked == false)
    {
      SetCheck(e.Node.Parent,
true);
      
return;
    }
    
    
//若当前节点所有同级节点没有勾选,父级节点要取消勾选
    
if (e.Node.Parent != null && e.Node.Parent.Checked)
    {
      
if (IsNoCheckedAll(e.Node.Parent.Nodes))
      SetCheck(e.Node.Parent,
false);
      
return;
    }
  }
  
  
private static void SetCheck(TreeNodeCollection nodes, bool value)
  {
    
if (nodes.Count == 0) return;
    
    TreeView tv
= nodes[0].TreeView;
    
    
try
    {
      tv.AfterCheck
-= OnTreeView_AfterCheck;
      
foreach (TreeNode node in nodes) node.Checked = value;
    }
    
finally
    {
      tv.AfterCheck +
= OnTreeView_AfterCheck;
    }
  }
  
  
private static void SetCheck(TreeNode node, bool value)
  {
    
try
    {
      node.TreeView.AfterCheck
-= OnTreeView_AfterCheck;
      node.Checked
= value;
    }
    
finally
    {
      node.TreeView.AfterCheck +
= OnTreeView_AfterCheck;
    }
  }
  
  
/// <summary>
  
/// 是否全部勾选
  
/// </summary>
  
/// <param name="nodes"></param>
  
/// <returns></returns>
  
public static bool IsCheckedAll(TreeNodeCollection nodes)
  {
    
int count = 0;
    
foreach (TreeNode N in nodes) if (N.Checked) count++;
    
return count == nodes.Count;
  }
  
  
/// <summary>
  
/// 是否全部没有勾选
  
/// </summary>
  
/// <param name="nodes"></param>
  
/// <returns></returns>
  
public static bool IsNoCheckedAll(TreeNodeCollection nodes)
  {
    
int count = 0;
    
foreach (TreeNode N in nodes) if (N.Checked == false) count++;
    
return count == nodes.Count;
  }
  
}

//来源:C/S框架网 | www.csframework.com | QQ:23404761




C/S框架网|原创精神.创造价值.打造精品

扫一扫加微信
C/S框架网作者微信 C/S框架网|原创作品.质量保障.竭诚为您服务



上一篇 下一篇