无法使用UserControl的重写BackColor属性

问题描述 投票:1回答: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

EDIT:我要完成的工作是在设置UserControl的BackColor属性时更改所选控件的BackColor,而使UserControl的背景色保持不变。

问题

由于某种原因,控件的背景色正根据我指定的变量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个回答
2
投票

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

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

一般而言,您应该

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

public new Color BackColor { get; set; }

在这种情况下,更改背景色不会更改控件的呈现。同样要设置OnPaintBackground使用的颜色,在构造函数中,您可以设置base.BackColor = Color.Blue;或其他内容。

示例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.