DrawString自定义控件文本未显示在winforms C#

时间:2016-05-26 12:03:09

标签: c# winforms c#-4.0

我创建了一个自定义控件并将其绑定到Form。我在控件中绘制图形文本并添加到Form。但它没有显示表格。这是我的代码。

//创建自定义控件

 public class DrawTextImage : Control
    {

        public void DrawBox(PaintEventArgs e, Size size)
        {
            e.Graphics.Clear(Color.White);
            int a = 0;
            SolidBrush textColor = new SolidBrush(Color.Black);
            using (SolidBrush brush = new SolidBrush(Color.Red))
            {

                e.Graphics.FillRectangle(brush, new Rectangle(a, a, size.Width, size.Height));
                e.Graphics.DrawString("Text", Font, textColor, new PointF(50, 50));
            }
        }
    }

//加载Form1

public Form1()
        {
            InitializeComponent();          

            DrawTextImage call = new DrawTextImage();
            call.Text = "TextControl";
            call.Name = "TextContrl";
            Size siz = new Size(200, 100);
            call.Location = new Point(0, 0);
            call.Visible = true;
            call.Size = siz;
            call.DrawBox(new PaintEventArgs(call.CreateGraphics(), call.ClientRectangle), siz);
            this.Controls.Add(call);
        }

对此有任何帮助,我做错了什么?

1 个答案:

答案 0 :(得分:5)

您应该使用控件自己的Paint事件,而不是您必须手动调用的自定义方法。

public class DrawTextImage : Control
{
    protected override void OnPaint(PaintEventArgs e)
    {
        e.Graphics.Clear(Color.White);
        int a = 0;
        SolidBrush textColor = new SolidBrush(Color.Black);
        using (SolidBrush brush = new SolidBrush(Color.Red))
        {
            //Note:  here you might want to replace the Size parameter with e.Bounds
            e.Graphics.FillRectangle(brush, new Rectangle(a, a, Size.Width, Size.Height));
            e.Graphics.DrawString("Text", Font, textColor, new PointF(50, 50));
        }
    }
}

取消对DrawBox的调用,这是不必要的。

每当需要重绘控件表面时,都会自动触发Paint事件。您可以使用控件的Invalidate()Refresh()方法在代码中自行提出此问题。