WinForm中Treeview实现根节点无选择框而子节点存在
2013-09-23 09:31
387 查看
由于需要,我不需要treeview控件的根节点上出现选择框(如下图)。自定义控件肯定是个办法,让我们先翻翻手册。
通过手册发现TreeView.DrawMode,用于指示TreeView 的节点或节点标签是否为自绘的还是系统绘制的,这是个枚举值。其中Normal为默认,代表完全有系统绘制;OwnerDrawText代表标签部分为手动绘制,其他元素由操作系统绘制,包括图标、复选框、加号和减号以及连接节点的线;OwnerDrawAll代表图标、复选框、加号和减号以及连接节点的线均为手工绘制。
因此我们可以设置此属性为 DrawMode=OwnerDrawAll 后,绑定TreeView.DrawNode事件就可以完成。下面是代码:
通过手册发现TreeView.DrawMode,用于指示TreeView 的节点或节点标签是否为自绘的还是系统绘制的,这是个枚举值。其中Normal为默认,代表完全有系统绘制;OwnerDrawText代表标签部分为手动绘制,其他元素由操作系统绘制,包括图标、复选框、加号和减号以及连接节点的线;OwnerDrawAll代表图标、复选框、加号和减号以及连接节点的线均为手工绘制。
因此我们可以设置此属性为 DrawMode=OwnerDrawAll 后,绑定TreeView.DrawNode事件就可以完成。下面是代码:
void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e) { if (e.Node.Parent == null) { Color backColor, foreColor; if ((e.State & TreeNodeStates.Selected) == TreeNodeStates.Selected) { backColor = SystemColors.Highlight; foreColor = SystemColors.HighlightText; } else if ((e.State & TreeNodeStates.Hot) == TreeNodeStates.Hot) { backColor = SystemColors.HotTrack; foreColor = SystemColors.HighlightText; } else { backColor = e.Node.BackColor; foreColor = e.Node.ForeColor; } if (this.treeView1.ShowPlusMinus) { #region 画一个“加号”表示未展开的 Pen pen = new Pen(Brushes.Black); Rectangle plusBound = new Rectangle(new Point(0, e.Bounds.Top), new Size(this.treeView1.Width, 18)); e.Graphics.DrawRectangle(pen, plusBound.X + 7, plusBound.Y + 2, 10, 10); e.Graphics.DrawLine(pen, plusBound.X + 9, plusBound.Top + 7, plusBound.Left + 15, plusBound.Top + 7); if (!e.Node.IsExpanded) { //如果节点未展开,则在减号中添加一条线,变成加号 e.Graphics.DrawLine(pen, plusBound.X + 12, plusBound.Top + 4, plusBound.Left + 12, plusBound.Top + 10); } #endregion } Rectangle newBounds = e.Node.Bounds; newBounds.X = 20; using (SolidBrush brush = new SolidBrush(backColor)) { e.Graphics.FillRectangle(brush, newBounds); } TextRenderer.DrawText(e.Graphics, e.Node.Text, this.treeView1.Font, newBounds, foreColor, backColor); if ((e.State & TreeNodeStates.Focused) == TreeNodeStates.Focused) { ControlPaint.DrawFocusRectangle(e.Graphics, newBounds, foreColor, backColor); } e.DrawDefault = false; } else { e.DrawDefault = true; } }
相关文章推荐
- WinForm中Treeview实现根节点无选择框而子节点存在
- 在Winform中的TreeView控件,实现选中/取消选中父节点则自动选择/取消选中对应子节点
- Winform使用C#实现Treeview节点"正在展开..."效果
- 详谈Winform中TreeView节点定位的实现方法
- winform下的treeview选取被选中的节点(递归实现)
- WinForm的TreeView实现Win7 Areo效果
- ASP.NET TreeView 用JS实现节点的单选功能
- C#Winform基础 treeview控件 点击按钮添加以textbox中为名称的根节点
- C# WinForm TreeView改变选中节点颜色,失去焦点时选中节点仍突显。
- 使用TreeView实现无限级扩展节点(原创)
- winform实现 绑定xml文档到treeview 控件
- c#,winform,treeview,选中节点,选中相应的全部子节点,取消节点,取消父节点,小技巧
- C#实现treeview节点上下左右自由移动
- Winform中Treeview实现按需加载的方法
- C# TreeView实现拖动节点时滚动条自动滚动
- C#Winform基础 treeview控件 点击按钮添加以textbox中为名称的根节点
- C# winform treeview node添加右键菜单并选中节点
- winform TreeView 节点选择
- C# WinForm TreeView改变选中节点颜色,失去焦点时选中节点仍突显。
- C#实现treeview节点上下左右自由移动