首先事件选择,选择的是MouseUp事件。为啥?由于凡是跟Check有关的,在选中父节点或者子节点,都会二次触发。而后发生的就是死循环。node
Up事件就能够避免二次触发。Down事件呢?那就触发AfterCheck事件了。事件选好了, 直接上代码。spa
处理思路:选中/取消当前节点,先选中其全部父节点,再选中其子节点code
注意平级节点处理:有平级节点选中,取消时须要遍历父节点。blog
如有一个平级节点处于选中,则父节点为选中。事件
若全部平级都没有选中的了,则父节点要取消选中class
/// <summary> /// 处理树节点选中和取消选中 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public static void treeView_MouseUpClick(object sender,MouseEventArgs e) { TreeView tree = sender as TreeView; if (tree == null) return; TreeNode node = tree.GetNodeAt(e.X, e.Y); if (node == null) return; SetTreeNodeCheckBoxState(node,true,node.Checked); SetTreeNodeCheckBoxState(node, false, node.Checked); } /// <summary> /// 处理父节点,子节点的选中 /// </summary> /// <param name="node">须要选中的树</param> /// <param name="isSetParentState">是否选中父节点</param> /// <param name="state">选中/不选中</param> public static void SetTreeNodeCheckBoxState(TreeNode node, bool isSetParentState, bool state) { if (node == null) return; node.Checked = state; if (isSetParentState && node.Parent != null && node.Checked==true) { SetTreeNodeCheckBoxState(node.Parent, isSetParentState, state); } else if (isSetParentState && node.Parent != null && node.Checked == false) { //处理取消选中 bool isSelect = false; foreach(TreeNode n in node.Parent.Nodes) { if (n.Checked==true) isSelect = true; } //平级都未有选中的才取消选中 if(isSelect==false) SetTreeNodeCheckBoxState(node.Parent, isSetParentState, state); } else if (!isSetParentState && node.Nodes!=null && node.Nodes.Count > 0) { foreach (TreeNode node2 in node.Nodes) { SetTreeNodeCheckBoxState(node2, isSetParentState, state); } } }