OnPaintBackground 方法永远不会为派生自 Button 的控件调用

Yod*_*oda 1 c# gradient winforms

我做了一个类GradientButton,它假设是一个填充渐变背景的按钮。

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

  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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

Iva*_*oev 5

这是因为Button该类设置了ControlStyles.Opaque标志,根据文档:

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

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

SetStyle(ControlStyles.Opaque, false);
Run Code Online (Sandbox Code Playgroud)

并且您的OnPaintBackground覆盖将被调用。

但是,这不会有很大帮助 - 设置标志是有原因的true-OnPaint绘制按钮的背景和面部,因此无论您做什么都不OnPaintBackground会对按钮外观产生任何影响。不幸的是,没有选择只绘制背景,因此您需要覆盖OnPaint并实际自己绘制所有内容