我希望从基本面板继承的面板无论在何处使用都具有固定的BackColor
。我的基本面板如下所示:
public class MyPanel
{
public override Color BackColor
{
get
{
return base.BackColor;
}
set
{
base.BackColor = Color.Red;
}
}
}
BackColor
未在示例表单的Designer.cs
文件中设置:
this.sampleControl.Font = new System.Drawing.Font("Tahoma", 8.25F,
System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.sampleControl.Location = new System.Drawing.Point(0, 0);
this.sampleControl.Margin = new System.Windows.Forms.Padding(5);
this.sampleControl.Name = "sampleControl";
this.sampleControl.Padding = new System.Windows.Forms.Padding(2, 0, 2, 2);
this.sampleControl.Size = new System.Drawing.Size(230, 100);
this.sampleControl.TabIndex = 1;
实际上在任何地方都没有颜色设置,所以我想它以某种方式从放置它的面板中获取属性。我该如何防止这种情况?
答案 0 :(得分:2)
怎么样:
public class MyPanel : Panel
{
private Color backColor = Color.Red;
public MyPanel()
{
// Set the color once
this.BackColor = backColor;
}
public override Color BackColor
{
get
{
return base.BackColor;
}
set
{
base.BackColor = backColor;
}
}
}
答案 1 :(得分:1)
只需在MyPanel构造函数中设置它。
BackColor=Color.Red;
除非您想阻止他人更改,否则您不需要override
。