c#Windows窗体-无法使用userControl的重写BackColor属性

问题描述 投票:0回答:1

场景

我正在使用UserControl创建自定义控件。

我正在尝试对UserControl的覆盖BackColor属性,以便在UserControl的BackColor属性更改时,控件的BackColor不会更改,并且值存储在变量BackColor_Value

这里是代码:-

Color BackColor_Value = Color.FromKnownColor(KnownColor.ActiveCaption);
[Browsable(true), EditorBrowsable(EditorBrowsableState.Always)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Bindable(true)]
//[AmbientValue(false)]
//[DefaultValue(typeof(Color), "ActiveCaption")]
public override Color BackColor
{
      get
      {
          return BackColor_Value;
      }
      set
      {
          BackColor_Value = value;
      }
 }

注意: BackColor仅存储在变量中,但未在任何地方使用。enter image description here

问题

由于某种原因,控件的背景色正根据我指定的变量BackColor_Value进行更改。

  • 为什么即使我重写了属性,默认功能仍会发生?
  • 我应该使用什么属性来阻止这种情况发生?

完整代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;

namespace MaterialUI_Control
{
    public partial class MaterialPanel : UserControl
    {
        public MaterialPanel()
        {
            InitializeComponent();
        }

        Color BackColor_Value = Color.FromKnownColor(KnownColor.ActiveCaption);
        [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        [Bindable(true)]
        [AmbientValue(false)]
        [DefaultValue(typeof(Color), "ActiveCaption")]
        public override Color BackColor
        {
            get
            {
                return BackColor_Value;
            }
            set
            {
                BackColor_Value = value;
                this.Refresh();
            }
        }
    }
}
c# winforms user-controls .net-3.5 gdi
1个回答
0
投票

BackColor属性将由OnPaintBackground方法用来呈现控件。如果要将BackColor属性用于其他目的,则可以使用以下任一选项:

  • 阴影/隐藏BackColor属性
  • 或替代OnPaintBackground并自己绘制背景

示例1-阴影/隐藏BackColor属性

public new Color BackColor { get; set; }

示例2-覆盖OnPaintBackground并自己绘制背景

protected override void OnPaintBackground(PaintEventArgs e)
{
    var method = typeof(Control).GetMethod("PaintBackground",
        System.Reflection.BindingFlags.Instance |
        System.Reflection.BindingFlags.NonPublic,
        null,
        new Type[] { typeof(PaintEventArgs), typeof(Rectangle), typeof(Color) },
        null);

    //Paint with a default constant back color, here for example Color.Red
    method.Invoke(this, new object[] { e, ClientRectangle, Color.Red });
}
© www.soinside.com 2019 - 2024. All rights reserved.