项目设计中要使用TreeView中CheckBox(在TreeView的属性中的CheckBoxes设为ture)。想达到一个这样的效果:
1、选中一个节点,则子节点的状态为当前节点的状态并设置展开或折叠。如:本来默认全部是折叠的,当选择Laboratory并使其Checked为true时,其子节点的状态都为true并展开节点,反之。关闭节点。
2、当子节点中至少一个节点状态为false时,其父节点状态仍为true,但是颜色变为灰色。
这个功能发生的事件是TreeView事件中的AfterCheck
代码如下:
- private void tvRoleAll_AfterCheck(object sender, System.Windows.Forms.TreeViewEventArgs e)
- {
- if (e.Action != TreeViewAction.Unknown)
- {
- SetNodeCheckStatus(e.Node, e.Node.Checked);
- SetNodeStyle(e.Node);
- }
- }
- private void SetNodeCheckStatus(TreeNode tn, bool Checked)
- {
- if (tn == null) return;
- foreach (TreeNode tnChild in tn.Nodes)
- {
- tnChild.Checked = Checked;
- SetNodeCheckStatus(tnChild, Checked);
- }
- TreeNode tnParent = tn;
- }
- private void SetNodeStyle(TreeNode Node)
- {
- int nNodeCount = 0;
- if (Node.Nodes.Count != 0)
- {
- foreach (TreeNode tnTemp in Node.Nodes)
- {
- if (tnTemp.Checked == true)
- nNodeCount++;
- }
- if (nNodeCount == Node.Nodes.Count)
- {
- Node.Checked = true;
- Node.ExpandAll();
- Node.ForeColor = Color.Black;
- }
- else if (nNodeCount == 0)
- {
- Node.Checked = false;
- Node.Collapse();
- Node.ForeColor = Color.Black;
- }
- else
- {
- Node.Checked = true;
- Node.ForeColor = Color.Gray;
- }
- }
-
- if (Node.Parent != null)
- SetNodeStyle(Node.Parent);
- }
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。