private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) { var node = e.Node; if (node == null) return; //根据父节点状态,全选或全消子节点 node.StateImageIndex = node.StateImageIndex == 1 ? 0 : 1; UpdateSubNodeCheckStatus(node); //确定子节点的父节点是否被选中(所有子节点选中时,父节点才选中) UpdateParentNodeCheckStatus(node); //根节点级别选择互斥 if (node.StateImageIndex != 1) return; var rootNode = GetRootByNode(node); UncheckNextNode(rootNode); UncheckPrevNode(rootNode); } private static TreeNode GetRootByNode(TreeNode node) { while (true) { if (node.Level == 0) { return node; } var parentNode = node.Parent; node = parentNode; } } private void UncheckPrevNode(TreeNode node) { if (node.PrevNode == null) return; node.PrevNode.StateImageIndex = 0; UpdateSubNodeCheckStatus(node.PrevNode); UncheckPrevNode(node.PrevNode); } private void UncheckNextNode(TreeNode node) { while (true) { if (node.NextNode == null) return; //node.NextNode.Checked = false; node.NextNode.StateImageIndex = 0; UpdateSubNodeCheckStatus(node.NextNode); node = node.NextNode; } } private static void UpdateParentNodeCheckStatus(TreeNode node) { var parentNode = node.Parent; if (parentNode == null) return; if (IsSubNodeAllCheck(parentNode)) { parentNode.StateImageIndex = 1; } else if (IsSubNodeAllUncheck(parentNode)) { parentNode.StateImageIndex = 0; } else { parentNode.StateImageIndex = 2; } UpdateParentNodeCheckStatus(parentNode); } private void UpdateSubNodeCheckStatus(TreeNode parentNode) { var node = parentNode; foreach (TreeNode subNode in node.Nodes) { subNode.StateImageIndex = node.StateImageIndex; UpdateSubNodeCheckStatus(subNode); } } //判断节点的子节点是否全选 private static bool IsSubNodeAllCheck(TreeNode parentNode) { return parentNode.Nodes.Cast<TreeNode>().All(subNode => subNode.StateImageIndex==1); } //判断同级的节点是否全不选 private static bool IsSubNodeAllUncheck(TreeNode parentNode) { return parentNode.Nodes.Cast<TreeNode>().All(subNode => subNode.StateImageIndex==0); }