我正在使用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仅存储在变量中,但未在任何地方使用。
由于某种原因,控件的背景色正根据我指定的变量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();
}
}
}
}
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 });
}