2012-02-22 39 views
0

我試圖從ToolStripLabel繼承:如何在構造函數中設置控件屬性(問題與設計師)

public class SeparatorLabel : ToolStripLabel 
{ 
    public SeparatorLabel() : base() 
    { 
     Margin = new Padding(5, 0, 5, 0); 
     Text = "ABC"; 
    } 
} 

然而,當我在窗體上放置這樣的控制,在Text屬性是取自在設計師的物業網格中輸入的值。

這當然是預料之中的,因爲我的構造函數在設置屬性網格的屬性之前被調用(窗體的InitializeComponent()),所以我的值被覆蓋。

現在的問題是 - 當從現有的控件繼承時,實現這種行爲的標準做法是什麼

我沒有實現它是覆蓋Text屬性包括一個空的制定者,而當我想以更新控制的Text,我手動設置base.Text方式:

public class SeparatorLabel : ToolStripLabel 
{ 
    public SeparatorLabel() : base() 
    { 
     Margin = new Padding(5, 0, 5, 0); 
     base.Text = "ABC"; 
    } 

    [Browsable(false)] 
    public override string Text 
    { 
     get 
     { 
      return base.Text; 
     } 
     set { } 
    } 
} 

這工作,但我不知道這是否是最佳做法。有沒有更多的傳統方式來實現我所需要的?

回答

0

你的例子不能編譯,因爲你的構造函數與你的類不同。您可以查看DesignerSerializationVisibility屬性,並將其設置爲Hidden

public SeparatorLabel() { 
    base.Margin = new Padding(5, 0, 5, 0); 
} 

[Browsable(false)] 
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] 
public new Padding Margin { 
    get { return base.Margin; } 
    set { 
    throw new Exception("This property is read only."); 
    } 
} 
+0

我糾正了我的例子中的錯誤(我沒有直接從我的代碼複製,因此無效的構造函數名稱)。 – 2012-02-23 07:09:37

相關問題