using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Windows.Forms; namespace RF.Sys.Helper { public class TvHelper { //定义一个用于保存静态变量的实例 private static TvHelper instance = null; //定义一个保证线程同步的标识 private static readonly object locker = new object(); //构造函数为私有,使外界不能创建该类的实例 private TvHelper() { } public static TvHelper Instance { get { if (instance == null) { lock (locker) { if (instance == null) instance = new TvHelper(); } } return instance; } } public void CheckParentNode(TreeNode node) { if (node.Parent != null) { if (node.Checked) { node.Parent.Checked = node.Checked; CheckParentNode(node.Parent); } else { bool select = false; foreach (TreeNode temp in node.Parent.Nodes) { select = select | temp.Checked; } if (select) node.Parent.Checked = true; else node.Parent.Checked = false; CheckParentNode(node.Parent); } } } public void CheckChildNode(TreeNode node) { if (node.Nodes.Count <= 0) return; foreach (TreeNode temp in node.Nodes) { temp.Checked = node.Checked; CheckChildNode(temp); } } } }
使用方式:使用右键快捷菜单实现。。。。。。
#region tv event private void btnCloseAllNode_Click(object sender, EventArgs e) { if (btnCloseAllNode.Text == "折叠所有节点") { this.tvCase.CollapseAll(); btnCloseAllNode.Text = "展开所有节点"; } else { this.tvCase.ExpandAll(); btnCloseAllNode.Text = "折叠所有节点"; } } private void btnCloseBandNode_Click(object sender, EventArgs e) { btnCloseBandNode.Text = "展开所有节点"; foreach (TreeNode networknode in this.tvCase.Nodes) { foreach (TreeNode bandnode in networknode.Nodes) { bandnode.Collapse(); } } } private void tvCase_AfterSelect(object sender, TreeViewEventArgs e) { TreeNode node = (TreeNode)e.Node; node.SelectedImageIndex = node.ImageIndex; } private void tvCase_AfterCheck(object sender, TreeViewEventArgs e) { TreeNode checknode = e.Node; if (e.Action != TreeViewAction.Unknown) { TvHelper.Instance.CheckChildNode(checknode); TvHelper.Instance.CheckParentNode(checknode); } } #endregion
博客内容主要用于日常学习记录,内容比较随意,如有问题,还需谅解!!!