WinForm控件TreeView 只部分节点显示 CheckBox
用过asp.net的应该知道,要在treeview中实现上述功能可以使用ShowCheckBox 属性指定那些节点显示checkbox哪些不显示,可是winform中的treeview只提供一个ShowCheckBoxes 属性,,要么全部节点显示checkbox,要不全部不显示,而指定节点没有ShowCheckBox 属性,下面就在winform的treeview中实现BS对应CheckBox 属性的功能
方法1:
a) 将TreeView的CheckBoxs属性设为false
b) 将TreeView的StateImageList属性关联一个imagelist组件,里面添加checkbox勾选图片和未勾选图片
c) 添加TreeView的NodeMouseClick事件,在事件中使用e.Node.StateImageIndex属性切换显示的图片(根据索引切换),可以创建一个泛型集合,比如List<string>,用于存放已打钩的节点项,从而方便切换打钩图片索引和未打钩图片索引
d) 缺点: 点击树节点所在行的任何位置都会触发NodeMouseClick事件,因为无法触发treeView1_AfterCheck和treeView1_NodeMouseClick事件,所以只能用NodeMouseClick事件
e) 原理: winform中treeview的checkbox项其实是使用图片显示的,选中是打钩的图片,未选中是未打钩的图片,关联的是StateImageList属性(默认为空,使用自带的图片)。所以如果要实现指定treenode显示checkbox,其它treenode不显示checkbox就需要使用TreeNode的StateImageList属性
方法2(建议):
1:初始化:
this.treeView1.DrawMode = System.Windows.Forms.TreeViewDrawMode.OwnerDrawAll;
this.treeView1.DrawNode += new System.Windows.Forms.DrawTreeNodeEventHandler(this.treeView_DrawNode);
:2: 设置条件控制需要显示checkbox
private void treeView_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
//隐藏节点前的checkbox
if (e.Node.ImageIndex <2)//此处设置前2级节点不显示选择框
HideCheckBox(this.treeView1, e.Node);
e.DrawDefault = true;
}
3:
private const int TVIF_STATE = 0x8;
private const int TVIS_STATEIMAGEMASK = 0xF000;
private const int TV_FIRST = 0x1100;
private const int TVM_SETITEM = TV_FIRST + 63;
private void HideCheckBox(TreeView tvw, TreeNode node)
{
TVITEM tvi = new TVITEM();
tvi.hItem = node.Handle;
tvi.mask = TVIF_STATE;
tvi.stateMask = TVIS_STATEIMAGEMASK;
tvi.state = 0;
SendMessage(tvw.Handle, TVM_SETITEM,IntPtr.Zero, ref tvi);
}
[StructLayout(LayoutKind.Sequential, Pack = 8, CharSet = CharSet.Auto)]
private struct TVITEM
{
public int mask;
public IntPtr hItem;
public int state;
public int stateMask;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpszText;
public int cchTextMax;
public int iImage;
public int iSelectedImage; public int cChildren; public IntPtr lParam;
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, ref TVITEM lParam);
//填充内容的代码略
就实现了 只显示部分checkbox
WinForm控件TreeView 只部分节点显示 CheckBox