winform treeview 复选框,父节点子节点联动Bug
这是Vista和Win7的Bug
有个屏蔽双击的解决方法(不完美,无法双击折叠展开节点了):
using System; using System.Windows.Forms; public class MyTreeView : TreeView { protected override void WndProc(ref Message m) { // Suppress WM_LBUTTONDBLCLK if (m.Msg == 0x203) { m.Result = IntPtr.Zero; } else base.WndProc(ref m); } }
public static class TreeViewCheck { /// <summary> /// 系列节点 Checked 属性控制 /// </summary> /// <param name="e"></param> public static void CheckControl(TreeViewEventArgs e) { if (e.Action != TreeViewAction.Unknown) { if (e.Node != null && !Convert.IsDBNull(e.Node)) { CheckParentNode(e.Node); if (e.Node.Nodes.Count > 0) { CheckAllChildNodes(e.Node, e.Node.Checked); } } } } #region 私有方法 //改变所有子节点的状态 private static void CheckAllChildNodes(TreeNode pn, bool IsChecked) { foreach (TreeNode tn in pn.Nodes) { tn.Checked = IsChecked; if (tn.Nodes.Count > 0) { CheckAllChildNodes(tn, IsChecked); } } } //改变父节点的选中状态,此处为所有子节点不选中时才取消父节点选中,可以根据需要修改 private static void CheckParentNode(TreeNode curNode) { bool bChecked = false; if (curNode.Parent != null) { foreach (TreeNode node in curNode.Parent.Nodes) { if (node.Checked) { bChecked = true; break; } } if (bChecked) { curNode.Parent.Checked = true; CheckParentNode(curNode.Parent); } else { curNode.Parent.Checked = false; CheckParentNode(curNode.Parent); } } } #endregion }
使用方法
private void treeView1_AfterCheck(object sender, TreeViewEventArgs e) { TreeViewCheck.CheckControl(e); }
参考:http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/9d717ce0-ec6b-4758-a357-6bb55591f956