分享

WinForm中Treeview实现根节点无选择框而子节点存在

 正则室 2018-06-07

WinForm中Treeview实现根节点无选择框而子节点存在


        由于需要,我不需要treeview控件的根节点上出现选择框(如下图)。自定义控件肯定是个办法,让我们先翻翻手册。

  通过手册发现TreeView.DrawMode,用于指示TreeView 的节点或节点标签是否为自绘的还是系统绘制的,这是个枚举值。其中Normal为默认,代表完全有系统绘制;OwnerDrawText代表标签部分为手动绘制,其他元素由操作系统绘制,包括图标、复选框、加号和减号以及连接节点的线;OwnerDrawAll代表图标、复选框、加号和减号以及连接节点的线均为手工绘制。

  因此我们可以设置此属性为 DrawMode=OwnerDrawAll 后,绑定TreeView.DrawNode事件就可以完成。下面是代码:

 

 

[csharp] view plain copy
  1. void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)  
  2. {  
  3.     if (e.Node.Parent == null)  
  4.     {  
  5.     Color backColor, foreColor;  
  6.     if ((e.State & TreeNodeStates.Selected) == TreeNodeStates.Selected)  
  7.     {  
  8.         backColor = SystemColors.Highlight;  
  9.         foreColor = SystemColors.HighlightText;  
  10.     }  
  11.     else if ((e.State & TreeNodeStates.Hot) == TreeNodeStates.Hot)  
  12.     {  
  13.         backColor = SystemColors.HotTrack;  
  14.         foreColor = SystemColors.HighlightText;  
  15.     }  
  16.     else  
  17.     {  
  18.         backColor = e.Node.BackColor;  
  19.         foreColor = e.Node.ForeColor;  
  20.     }  
  21.     if (this.treeView1.ShowPlusMinus)  
  22.     {  
  23.         #region 画一个“加号”表示未展开的  
  24.         Pen pen = new Pen(Brushes.Black);  
  25.         Rectangle plusBound = new Rectangle(new Point(0, e.Bounds.Top), new Size(this.treeView1.Width, 18));  
  26.         e.Graphics.DrawRectangle(pen, plusBound.X + 7, plusBound.Y + 2, 10, 10);  
  27.         e.Graphics.DrawLine(pen, plusBound.X + 9, plusBound.Top + 7, plusBound.Left + 15, plusBound.Top + 7);  
  28.         if (!e.Node.IsExpanded)  
  29.         {  
  30.         //如果节点未展开,则在减号中添加一条线,变成加号  
  31.         e.Graphics.DrawLine(pen, plusBound.X + 12, plusBound.Top + 4, plusBound.Left + 12, plusBound.Top + 10);  
  32.         }  
  33.         #endregion  
  34.     }  
  35.     Rectangle newBounds = e.Node.Bounds;  
  36.     newBounds.X = 20;  
  37.   
  38.     using (SolidBrush brush = new SolidBrush(backColor))  
  39.     {  
  40.         e.Graphics.FillRectangle(brush, newBounds);  
  41.     }  
  42.   
  43.     TextRenderer.DrawText(e.Graphics, e.Node.Text, this.treeView1.Font, newBounds, foreColor, backColor);  
  44.   
  45.     if ((e.State & TreeNodeStates.Focused) == TreeNodeStates.Focused)  
  46.     {  
  47.         ControlPaint.DrawFocusRectangle(e.Graphics, newBounds, foreColor, backColor);  
  48.     }  
  49.   
  50.     e.DrawDefault = false;  
  51.     }  
  52.     else  
  53.     {  
  54.     e.DrawDefault = true;  
  55.     }  
  56. }  

个人分类: .Net技术

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多