簡體   English   中英

如何以編程方式將自定義控件添加到表單並顯示它?

[英]How to programmatically add a Custom Control to a Form and show it?

我正在嘗試通過以編程方式使用另一個 class 將 Label 添加到 Windows 表單中。 我的 Label 沒有出現在表單中。
我不知道我哪里錯了。

private void Form1_Load(object sender, EventArgs e)
{
     Ticker ticker = new Ticker("ASDF");
     ticker.display();
}

public class Ticker : Label
{
     string labelText;
     Label label = new Label();

     public Ticker(string _labelText)
     {
         labelText = _labelText;
     }
     public void display()
     {
         label.Text = labelText;

         Controls.Add(label);
     }
}

您可以對 Ticker 自定義控件進行一些更改:

  • 你不需要你的自定義控件中創建一個新的 Label:你的控件已經是一個 Label,使用this引用來設置它的屬性(另見this關鍵字(C#參考) )。
  • Text 是當前標簽的文本 ( this.Text )。 如果您出於其他原因需要它的副本(通常是自定義繪畫,因此有時您需要清除文本),請存儲它。
    Controls指的是當前的class object:它是一個Control,所以它有一個Controls屬性,它獲取一個Control的子Controls的ControlCollection
  • 您還需要在其ParentClientRectangle中指定定義自定義控件的 position 的 Point 。
  • 即使它並不總是需要,也可以在自定義控件中添加一個無參數構造函數:如果/當它實際需要時,你就已經在那里了。

如果您不想像往常一樣從外部設置父控件(例如, var label = new Label(); this.Controls.Add(label); ),您需要傳遞控件的引用,這將成為您的自定義 Label 的父控件。
您可以使用此引用 - 一個Control類型的引用 - 並將您的 Label 添加到您收到的 Control 引用的 Controls 集合中:

// You want to store a reference to this Control if you need it later...
private Ticker ticker = null;

private void Form1_Load(object sender, EventArgs e)
{
    //... or just declare it with: var ticker = new Ticker() if you don't
    ticker = new Ticker("The Label's Text");
    // [this] of course refers the current class object, Form1
    ticker.Display(this, new Point(100, 100));
    // Or, display the Label inside a Panel, child of Form1
    // Note: if you don't comment the next line, the Label will be moved to panel1
    ticker.Display(this.panel1, new Point(10, 50));
}

在這里,我重載了Display()方法,因此它同時接受 Parent 引用和Point值,用於 position 其父客戶區域內的控件。
自定義 Label 也調用BringToFront() ,以避免出現Parent的其他一些已經存在的子控件下。

public class Ticker : Label
{
    public Ticker() : this("ticker") { }
    public Ticker(string labelText) => this.Text = labelText;

    public void Display(Control parent) => Display(parent, Point.Empty);
    public void Display(Control parent, Point position)
    {
        this.Location = position;
        parent.Controls.Add(this);
        this.BringToFront();
    }
}

暫無
暫無

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

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