簡體   English   中英

擴展System.Windows.Forms.Button並更改c#中的默認Text

[英]Extend a System.Windows.Forms.Button and change default Text in c#

我通過擴展System.Windows.Forms.Button類創建了一個自定義控件按鈕。

我在新類的構造函數中設置了默認的.Text .Width和.Height。

當我將此控件放到窗體上時,IDE足夠聰明,可以注意構造函數中指定的Width和Height並將這些屬性分配給正在創建的新按鈕,但是它會忽略Text屬性,並分配.Text該按鈕為“ ucButtonConsumables1”

有沒有一種方法可以將.Text設置為我選擇的默認值?

public partial class ucButtonConsumables : System.Windows.Forms.Button {
    public ucButtonConsumables() {

        this.Text = "Consumables";                   
        this.Width = 184;
        this.Height = 23;

        this.Click += new EventHandler(ucButtonConsumables_Click);

    }

    void ucButtonConsumables_Click(object sender, EventArgs e) {

        MessageBox.Show("Button Clicked")

    }

}

設計器序列化的“隱藏文本”屬性:

[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override string Text
{
    get { return base.Text; }
    set { base.Text = value; }
}

或使用默認值創建設計器:

public class ConsumablesButtonDesigner : System.Windows.Forms.Design.ControlDesigner
{
    public override void OnSetComponentDefaults()
    {
        base.OnSetComponentDefaults();
        Control.Text = "Consumables";
    }
}

並將該設計師提供給您的按鈕:

[Designer(typeof(ConsumablesButtonDesigner))]
public class ucButtonConsumables : Button
{
   //...
}

您必須重寫派生類中的Text屬性才能進行更改。

public override string Text { get; set; }

是的,不可能在構造函數中執行此操作。 如果您確定不會再次更改該值,請按照這種方式進行操作。 重寫Text屬性並返回常量。

    public override string Text
    {
        get
        {
            return "Consumables";
        }
        set
        {
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM