2012-02-14 42 views
0

我想要一個從基礎面板繼承的面板,無論使用何處,都要有固定的BackColor。我的基本面板看起來是這樣的:如何防止控件的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; 

其實是沒有顏色的任何地方設定,所以我想它在某種程度上得到它被放置在面板上的財產。我怎樣才能防止這種情況?

+1

有什麼實際的顏色,你看到了什麼? – ken2k 2012-02-14 16:48:17

+0

父控件的背景色,即如果父面板是藍色,則此控件也將爲藍色。 – xsl 2012-02-14 16:49:49

回答

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; 
     } 
    } 
} 
+0

這是有效的。謝謝。有沒有其他的方式來做到這一點,而不是重複構造函數中的所有屬性? – xsl 2012-02-14 17:00:53

+0

@xsl您是否覆蓋面板的其他屬性? – ken2k 2012-02-14 17:03:42

+0

到目前爲止只有前景色。但未來可能會有更多。 – xsl 2012-02-14 18:10:25

1

只需在MyPanel構造函數中設置即可。

BackColor=Color.Red; 

,除非你想防止他人更改它,您不需要override

+0

我想從一個地方控制backcolor屬性,而不是到處使用控件。 – xsl 2012-02-14 16:53:22

+0

你是什麼意思? – ispiro 2012-02-14 16:54:43

+0

從MyPanel繼承的所有控件都應該有一個固定的BackColor,無論它們在哪裏使用,都不需要手動設置屬性。 – xsl 2012-02-14 16:56:51