同步TreeView中父结点和子结点的状态[以及Treeview的bug]
此代码仅仅是二级结点,即父结点下面只有一层子结点,只有两层结构
/// <summary> /// 某个结点的CheckBox被选中 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void treeViewDevices_AfterCheck(object sender, TreeViewEventArgs e) { //将父结点的状态同步给子结点 setChildNodeCheckedState(e.Node,e.Node.Checked); if (e.Node.Parent != null) { setParentNodeCheckedState(e.Node); } } /// <summary> /// 选中结点之后,自动选择当前结点所有的子结点 /// </summary> /// <param name="currNode">当前结点</param> /// <param name="state">选中状态</param> private void setChildNodeCheckedState(TreeNode currNode, bool state) { TreeNodeCollection nodes = currNode.Nodes; foreach (TreeNode tn in nodes) { tn.Checked = state; setChildNodeCheckedState(tn, state); } } /// <summary> /// 选中当前结点之后,设置父结点的状态 /// </summary> /// <param name="currNode"></param> private void setParentNodeCheckedState(TreeNode currNode) { if (currNode.Checked)//当前结点为选中状态 { if (currNode.Parent.Checked==false) { treeViewDevices.AfterCheck -= new System.Windows.Forms.TreeViewEventHandler(this.treeViewDevices_AfterCheck); currNode.Parent.Checked = true;//选中父结点的时候,会触发选中事件,导致又重复选中子结点,所以要先注销选中事件,然后再注册 treeViewDevices.AfterCheck += new System.Windows.Forms.TreeViewEventHandler(this.treeViewDevices_AfterCheck); } } else//当前结点未选中 { bool flag = false; TreeNodeCollection parentNodes = currNode.Parent.Nodes; foreach (TreeNode treenode in parentNodes) { if (treenode.Checked) { flag = true; break; } } if (flag)//说明父结点的状态应该为选中状态 { if (currNode.Parent.Checked == false) { treeViewDevices.AfterCheck -= new System.Windows.Forms.TreeViewEventHandler(this.treeViewDevices_AfterCheck); currNode.Parent.Checked = true;//选中父结点的时候,会触发选中事件,导致又重复选中子结点,所以要先注销选中事件,然后再注册 treeViewDevices.AfterCheck += new System.Windows.Forms.TreeViewEventHandler(this.treeViewDevices_AfterCheck); } } else//无需选中父结点 { if (currNode.Parent.Checked == true) { currNode.Parent.Checked = false; } } } }
TreeView的bug在这里有解决方法
http://social.msdn.microsoft.com/Forums/windows/en-US/9d717ce0-ec6b-4758-a357-6bb55591f956/possible-bug-in-net-treeview-treenode-checked-state-inconsistent?forum=winforms