【问题标题】:How to make a custom control be updated in designer?如何在设计器中更新自定义控件?
【发布时间】:2016-05-31 18:20:54
【问题描述】:

我创建了一个派生自 Panel 的自定义控件。 一切正常,除了在设计器中我的控件只有在失去焦点时才会重绘。 我错过了什么?

这里是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);
        }
    }
}

这是在 xPanel1 内移动 label1 之后,在失去焦点之前拍摄的打印屏幕。

【问题讨论】:

  • 你能打印屏幕吗?
  • 您忘记发布您的控件的代码。
  • 您是否使用 '+=" 注册了 OnPaint 事件?
  • 不要使用pe.ClipRectangle。请根据您的要求使用DisplayRectangleClientRactangle

标签: c# winforms


【解决方案1】:

您的问题是因为在控件上绘画时使用了pe.ClipRectangle。 不要使用pe.ClipRectangle。请根据您的要求使用DisplayRectangleClientRactangle

当您在pe.ClipRectangle 边界内绘制时,如您所见,绘制将在控件的最小无效部分上完成。

注意:

  • 您不需要在构造函数中包含InitializeComponent();,除非您使用面板组件的设计器向其中添加一些其他组件。

  • 如果你使用了DisplayRectangle,那么在FillRectangle方法中,使用0,5而不是DisplayRectangle.X + 5, DisplayRectangle.Y

  • 如果你想画一个自定义的GroupBox,你可以看看Custom GroupBox BackColor to Transparent

【讨论】:

  • 非常感谢。我用过ClientRectangle,问题就解决了。
猜你喜欢
  • 1970-01-01
  • 2012-09-06
  • 1970-01-01
  • 1970-01-01
  • 2013-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多