Winform TreeView OwnerDrawText

winform 开发,使用TreeView控件,需要对节点单独设置颜色,

控件本身有焦点时,选中的样式是一样的,所以使用OwnerDrawText 自己实现使用自定义颜色绘制文本



        private Brush treeBgColor = new SolidBrush(Color.FromArgb(51, 153, 255));
        private void treeViewImg_DrawNode(object sender, DrawTreeNodeEventArgs e)

        {


            if (!e.Node.IsVisible) {//节点不可见时
                e.DrawDefault = true;
                return;
            }

            //e.DrawDefault = true; //这里用默认颜色即可,只需要在TreeView失去焦点时选中节点仍然突显  
            //return;
            //or  自定义颜色  
            if ((e.State & TreeNodeStates.Selected) != 0)
            {
                //为蓝底白字  
                e.Graphics.FillRectangle(treeBgColor, e.Node.Bounds);
                Brush fontBrush = e.Node.ForeColor == errorColor ? Brushes.Red : Brushes.White;
                Font nodeFont = e.Node.NodeFont;
                if (nodeFont == null) nodeFont = ((TreeView)sender).Font;


                e.Graphics.DrawString(e.Node.Text, nodeFont, fontBrush, Rectangle.Inflate(e.Bounds, 2, 0));
                //, Rectangle.Inflate(e.Bounds, 0, 0));
            }
            else if (e.Node == selectedTreeNode)
            {
                e.Graphics.FillRectangle(treeBgColor, e.Node.Bounds);
                Brush fontBrush = e.Node.ForeColor == errorColor ? Brushes.Red : Brushes.White;
                Font nodeFont = e.Node.NodeFont;
                if (nodeFont == null) nodeFont = ((TreeView)sender).Font;


                e.Graphics.DrawString(e.Node.Text, nodeFont, fontBrush, Rectangle.Inflate(e.Bounds, 2, 0));
                //e.Graphics.DrawString(e.Node.Text, nodeFont, fontBrush, Rectangle.Inflate(e.Bounds, 0, 0));
            }
            else
            {
                if (e.Node.ForeColor.A == 0)//初始化时
                {
                    e.DrawDefault = true;
                    return;
                }
                using (Brush nBrush = new SolidBrush(e.Node.BackColor))
                using (Brush fontBrush = new SolidBrush(e.Node.ForeColor))
                {
                    e.Graphics.FillRectangle(nBrush, e.Node.Bounds);
                    //Brush fontBrush = e.Node.ForeColor == errorColor ? Brushes.Red : Brushes.White;
                    Font nodeFont = e.Node.NodeFont;
                    if (nodeFont == null) nodeFont = ((TreeView)sender).Font;


                    e.Graphics.DrawString(e.Node.Text, nodeFont, fontBrush, Rectangle.Inflate(e.Bounds, 2, 0));
                    //, Rectangle.Inflate(e.Bounds, 0, 0));
                    //   e.DrawDefault = true;
                }
            }


        }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值