永远不会为从Button派生的控件调用OnPaintBackground方法 [英] The OnPaintBackground method is never invoked for control derived from Button

查看:53
本文介绍了永远不会为从Button派生的控件调用OnPaintBackground方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个类 GradientButton ,该类假定是一个填充了渐变背景的Button。

I've made a class GradientButton which suppose to be a Button which is filled with gradient background.

我在 OnPaintBackground()方法中绘制渐变填充。不幸的是,它从未被调用过,当然我通过工具箱在 Form 中添加了 GradientButton

I draw gradient filling in the OnPaintBackground() method. Unfortunately it is never invoked, of course I added a GradientButton to a Form via toolbox:

  public class GradientButton : Button {

        public Color Color1 { get; set; }
        public Color Color2 { get; set; }

        public float Angle { get; set; }

        public GradientButton() {
            Color1 = Color.YellowGreen;
            Color2 = Color.LightGreen;
            Angle = 30;
        }



        protected override void OnPaintBackground(PaintEventArgs e) {
            base.OnPaintBackground(e);
            Debug.WriteLine("This never prints");
            using (LinearGradientBrush brush = new LinearGradientBrush(this.ClientRectangle,
                                                                       Color1,
                                                                       Color2,
                                                                       Angle)) {
                e.Graphics.FillRectangle(brush, this.ClientRectangle);
            }
        }
        protected override void OnResize(EventArgs e) {
            base.OnResize(e);
            Invalidate();
        }
    }

问题:如何填写渐变的按钮背景?为什么不调用 OnPaintBackground ?据我所知,应在 OnPaint 方法之前调用。

Question: How fill the button's background with the gradient? Why OnPaintBackground is not invoked? As far as I know it should be calledbefore OnPaint method.

推荐答案

这是因为 Button 类具有 ControlStyles.Opaque 标志集,根据文档:

This is because the Button class has ControlStyles.Opaque flag set, which according to the documentation:


如果为true,则将控件绘制为不透明的,并且不绘制背景。

If true, the control is drawn opaque and the background is not painted.

您可以在类构造函数中将其关闭

You can turn it off in your class constructor

SetStyle(ControlStyles.Opaque, false);

和您的 OnPaintBackground 覆盖将被调用。

and your OnPaintBackground override will be invoked.

但是,这并没有太大帮助-有一个将标志设置为 true 的原因- OnPaint 同时绘制按钮的背景和外观,因此您在 OnPaintBackground 中所做的任何操作均不会影响按钮出现。不幸的是,没有办法只绘制背景,因此您需要覆盖 OnPaint 并实际绘制所有内容

However, it would not help a lot - there is a reason the flag to be set to true - the OnPaint draws both background and face of the button, so whatever you do in OnPaintBackground will not have any affect of the button appearance. Unfortunately there is no option to paint just the background, so you need to override the OnPaint and actually draw everything yourself.

这篇关于永远不会为从Button派生的控件调用OnPaintBackground方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆