简体   繁体   中英

How to make a custom control be updated in designer?

I have created a custom control derived from Panel. Everything works fine, except that in designer my control is only redrawn when it loses focus. What am I missing?

Here is the code of CustomControl.cs

using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace Picwing
{
    public partial class xPanel : Panel
    {
        private SizeF textSize;

        public xPanel() {
            InitializeComponent();
        }

        [Browsable(true)]
        public override string Text {
            get { return base.Text; }
            set { base.Text = value; }
        }

        protected override void OnPaint(PaintEventArgs pe) {
            base.OnPaint(pe);
            textSize = pe.Graphics.MeasureString(Text, Font);
            pe.Graphics.DrawRectangle(new Pen(ForeColor, 1), pe.ClipRectangle.X, pe.ClipRectangle.Y + textSize.Height / 2, pe.ClipRectangle.Width - 1, pe.ClipRectangle.Height - textSize.Height / 2 - 1);
            pe.Graphics.FillRectangle(new SolidBrush(BackColor), 5, 0, textSize.Width, textSize.Height);
            pe.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), pe.ClipRectangle.X + 6, pe.ClipRectangle.Y);
        }
    }
}

This is a print screen taken after moving label1 inside xPanel1, before it loses focus. 在此处输入图片说明

Your problem is because of using pe.ClipRectangle while painting on control. Don't use pe.ClipRectangle . Use DisplayRectangle or ClientRactangle instead, based on your requirement.

When you draw in pe.ClipRectangle bounds, as you can see, the drawing will be done on the smallest invalidated part of your control.

Note:

  • You don't need to have InitializeComponent(); in constructor unless you use designer of your panel component to add some other components to it.

  • If you used DisplayRectangle , then in the FillRectangle method, instead of 0,5 use DisplayRectangle.X + 5, DisplayRectangle.Y .

  • If you are trying you draw a custom GroupBox , you can take a look at Custom GroupBox BackColor to Transparent

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM