承接上篇文章,本文將詳細展示自訂元件 LabeledTextBox 的完整原始碼實作,包含元件結構定義、屬性封裝與初始化邏輯。
using System.Windows.Forms;
namespace MyControls
{
// 繼承 UserControl 建立複合元件
public class LabeledTextBox : UserControl
{
// 元件內部結構:一個 Label + 一個 TextBox
private Label myLabel;
private TextBox myTextBox;
public LabeledTextBox()
{
InitializeComponent();
}
public void InitializeComponent()
{
// 建立標籤
myLabel = new Label();
myLabel.Location = new System.Drawing.Point(0, 0);
myLabel.Size = new System.Drawing.Size(100, 20);
// 建立文字方塊
myTextBox = new TextBox();
myTextBox.Location = new System.Drawing.Point(105, 0);
myTextBox.Size = new System.Drawing.Size(100, 20);
// 設定整體元件大小
this.Size = new System.Drawing.Size(205, 20);
// 將子元件加入容器
this.Controls.Add(myLabel);
this.Controls.Add(myTextBox);
}
// 覆寫 Text 屬性,委派給內部 TextBox
public override string Text
{
get { return myTextBox.Text; }
set { myTextBox.Text = value; }
}
// 自訂 LabelText 屬性,委派給內部 Label
public string LabelText
{
get { return myLabel.Text; }
set { myLabel.Text = value; }
}
}
}
LabeledTextBox 繼承自 UserControl,內部封裝了 Label 與 TextBox 兩個子元件,透過座標定位排版,對外呈現為單一整體元件。
myTextBox.TextmyLabel.Text這種「屬性委派」設計讓使用者能像操作單一元件一樣存取內部子元件的屬性,封裝性極佳。
將元件置於 MyControls 命名空間,避免類別名稱衝突,方便客戶端匯入使用。
元件原始碼完成後,下一篇將示範:
csc /t:library 編譯為 control.dllsample.cs 參考並使用此元件