将油漆代码添加到轨迹栏控件

时间:2016-01-17 16:53:10

标签: c#

我想在轨迹栏控件的刻度标记上添加文本标签。最初一切看起来都很好但是当拖动轨迹栏的拇指时,我的文字标签就消失了。这里发生了什么?

这是我的代码:

public class DateTimeTrackBar : TrackBar
{
    public DateTimeTrackBar()
    {
        :
        SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw, true);
    }
    :
    protected override void OnPaint(PaintEventArgs e)
    {     
        base.SetStyle(ControlStyles.UserPaint, false);

        base.Refresh();

        if (ShowLabels)
            DrawLabels(e);

        base.SetStyle(ControlStyles.UserPaint, true);

        //base.OnPaint(e);
    }

    protected virtual void DrawLabels(PaintEventArgs e)
    {
        int nNumTicks = GetNumTicks(this);

        if (nNumTicks > 0)
        {
            PointF[] TickLocs = GetTickLocations(nNumTicks);
            string[] TickLabels = GetTickLabels(nNumTicks);

            using (Font ArialFnt = new Font("Arial", 6, FontStyle.Regular))
            {
                using (Brush GrayBrush = new SolidBrush(Color.Gray))
                {
                    float fTickLabelLocOffset;

                    for (int i = 0; i < nNumTicks; i++)
                    {
                        if (!ShowMinMaxLabels && ((i == 0) || (i == (nNumTicks - 1))))
                            continue;

                        if (i == 0)
                            fTickLabelLocOffset = 0.0f;
                        else
                        {
                            SizeF Size = e.Graphics.MeasureString(TickLabels[i], ArialFnt);

                            if (i == (nNumTicks - 1))
                                fTickLabelLocOffset = Size.Width;
                            else
                                fTickLabelLocOffset = (Size.Width / 2.0f);
                        }

                        PointF TickLabelLoc = new PointF(TickLocs[i].X - fTickLabelLocOffset, TickLocs[i].Y + 8);

                        e.Graphics.DrawString(TickLabels[i], ArialFnt, GrayBrush, TickLabelLoc);
                    }
                }
            }
        }
    }
    :
}

1 个答案:

答案 0 :(得分:0)

此处的标准约定是不设置UserPaint样式,在覆盖方法中调用base.OnPaint(),然后在调用base.OnPaint()之后呈现自定义图形,类似对此:

protected override void OnPaint(PaintEventArgs e)
{     
    base.OnPaint(e);

    if (ShowLabels)
        DrawLabels(e);
}

根据https://msdn.microsoft.com/en-us/library/system.windows.forms.control.setstyle(v=vs.110).aspx Control.SetStyle()的文档以及https://msdn.microsoft.com/en-us/library/system.windows.forms.controlstyles(v=vs.110).aspxControlStyles枚举,请考虑以下事项:

  • 您不应该反复调用SetStyle()来更改标记(如OnPaint()方法中所发生的那样)。初始化控件时,应将这些设置为一次。
  • 当您将UserPaint标志设置为true时,您将告诉Windows以下内容。这可能不是你的意图:
  

如果为true,则控件会自行绘制而不是操作系统   这样做。如果为false,则不会引发Paint事件。这种风格而已   适用于从Control派生的类。