您的位置:首页 > 其它

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

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

  通过手册发现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;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: