[英]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 自定義控件進行一些更改:
this
引用來設置它的屬性(另見this
關鍵字(C#參考) )。this.Text
)。 如果您出於其他原因需要它的副本(通常是自定義繪畫,因此有時您需要清除文本),請存儲它。Controls
指的是當前的class object:它是一個Control,所以它有一個Controls
屬性,它獲取一個Control的子Controls的ControlCollection
。 如果您不想像往常一樣從外部設置父控件(例如, 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.