這個範例將示範如何建立一個包含控制項集合的類別
其包含以下幾個主要功能:
1. button1_Click(),在父表單中實作控制項集合的物件,每個物件都有相同的功能
2. button2_Click(),在新的表單Form2中實作控制項集合的物件,每個新表單中的物件都有相同功能
3. Cell 類別,定義控制項集合中的成員:按鈕Button、標籤Label,以及Button的Click事件
4. Cell2 類別,繼承自Cell的衍生類別,實作包含控制項集合在內的新表單
程式範例:
1. button1_Click(),在父表單中實作控制項集合的物件,每個物件都有相同的功能
private int iGap = 0;
private void button1_Click(object sender, EventArgs e)
{
Control.ControlCollection collection = new Control.ControlCollection(this);
// 實作 cell, 並定義這個群組物件的在表單中的左上角座標
Cell c = new Cell(iGap, 50);
// 取得由 class Cell{} 所包裝的控制項集合 (Button*2, Label*1)
collection = c.GetCell();
// 在表單上新增已包裝的控制項
for (int i = 0; i < 3; i++)
Controls.Add(collection[i]);
// 指示每個物件的水平間隔
iGap += 80;
}
2. button2_Click(),在新的表單Form2中實作控制項集合的物件,每個新表單中的物件都有相同功能
private void button2_Click(object sender, EventArgs e)
{
Control.ControlCollection collection = new Control.ControlCollection(this);
// 實作 cell2, 並定義這個群組物件的在表單中的左上角座標
Cell2 c = new Cell2(50, 50);
// 實作一個含有控制項集合的新表單
c.NewForm();
}
3. Cell 類別,定義控制項集合中的成員:按鈕Button、標籤Label,以及Button的Click事件
public class Cell
{
protected Button minus, plus;
protected Label lab;
protected int iCurrent;
public Cell() { }
public Cell(int iLeft, int iTop)
{
// new Button minus, Button plus, Label lab
this.minus = new Button();
this.minus.Text = "-";
this.minus.Location = new System.Drawing.Point(iLeft, iTop);
this.plus = new Button();
this.plus.Text = "+";
this.plus.Location = new System.Drawing.Point(iLeft, (5 + minus.Bottom));
this.lab = new Label();
this.lab.Text = "0";
this.lab.Size = new System.Drawing.Size(33, 12);
this.lab.Location = new System.Drawing.Point(iLeft, (5 + plus.Bottom));
// 訂閱Click事件
this.minus.Click += new System.EventHandler(this.minus_Click);
this.plus.Click += new System.EventHandler(this.plus_Click);
}
public Control.ControlCollection GetCell()
{
Control owner = new Control();
Control.ControlCollection collection = new Control.ControlCollection(owner);
// 打包3個控制項
collection.Add(this.minus);
collection.Add(this.plus);
collection.Add(this.lab);
return collection;
}
private void minus_Click(object sender, EventArgs e)
{
iCurrent--;
this.lab.Text = iCurrent.ToString();
}
private void plus_Click(object sender, EventArgs e)
{
iCurrent++;
this.lab.Text = iCurrent.ToString();
}
}
4. Cell2 類別,繼承自Cell的衍生類別,實作包含控制項集合在內的新表單
public class Cell2 : Cell
{
public Cell2(int iLeft, int iTop) : base(iLeft, iTop) { }
public void NewForm()
{
Form f = new Form2();
f.Show();
Control.ControlCollection collection = new Control.ControlCollection(f);
// 取得由 class Cell{} 所包裝的控制項集合 (Button*2, Label*1)
collection = this.GetCell();
// 在表單上新增已包裝的控制項
for (int i = 0; i < 3; i++)
f.Controls.Add(collection[i]);
}
相關資料參考 msdn: System.Windows.Forms.Control.ControlCollection



請先 登入 以發表留言。