close
放入三個button和一個panel元件
待會利用三個按鈕點擊去動態載入不同模組(即使用者控制元件)
專案加入使用者控制元件(User Control)
命名ucModule1.cs
重複上述動作,命名ucModule2.cs
重複上述動作,命名ucModule3.cs
完成後
點選ucModule1.cs,接著按滑鼠右鍵點選選單View Code
1. Line3: 加入私有靜態成員變數_instance
2. Line 4~12: 加入公開靜態屬性 Instance
1: public partial class ucModule1 : UserControl
2: {
3: private static ucModule1 _instance;
4: public static ucModule1 Instance
5: {
6: get
7: {
8: if(_instance==null)
9: {
10: _instance = new ucModule1();
11: }
12: return _instance;
13: }
14: }
15: public ucModule1()
16: {
17: InitializeComponent();
18: }
19: }
ucModule2.cs仿照ucModule1.cs步驟
1: public partial class ucModule2 : UserControl
2: {
3: private static ucModule2 _instance;
4: public static ucModule2 Instance
5: {
6: get
7: {
8: if (_instance == null)
9: {
10: _instance = new ucModule2();
11: }
12: return _instance;
13: }
14: }
15: public ucModule2()
16: {
17: InitializeComponent();
18: }
19: }
ucModule3.cs仿照ucModule1.cs步驟
1: public partial class ucModule3 : UserControl
2: {
3: private static ucModule3 _instance;
4: public static ucModule3 Instance
5: {
6: get
7: {
8: if (_instance == null)
9: {
10: _instance = new ucModule3();
11: }
12: return _instance;
13: }
14: }
15: public ucModule3()
16: {
17: InitializeComponent();
18: }
19: }
回到主Form1.cs,滑鼠點擊按鈕1事件加入下列
1: private void btnModule1_Click(object sender, EventArgs e)
2: {
3: if(!panel1.Controls.Contains(ucModule1.Instance))
4: {
5: panel1.Controls.Add(ucModule1.Instance);
6: ucModule1.Instance.Dock = DockStyle.Fill;
7: ucModule1.Instance.BringToFront();
8: }else
9: {
10: ucModule1.Instance.BringToFront();
11: }
12: }
按鈕2滑鼠點擊事件類似按鈕1
1: private void btnModule2_Click(object sender, EventArgs e)
2: {
3: if (!panel1.Controls.Contains(ucModule2.Instance))
4: {
5: panel1.Controls.Add(ucModule2.Instance);
6: ucModule2.Instance.Dock = DockStyle.Fill;
7: ucModule2.Instance.BringToFront();
8: }
9: else
10: {
11: ucModule2.Instance.BringToFront();
12: }
13:
14: }
按鈕3滑鼠點擊事件類似按鈕1
1: private void btnModule3_Click(object sender, EventArgs e)
2: {
3: if (!panel1.Controls.Contains(ucModule3.Instance))
4: {
5: panel1.Controls.Add(ucModule1.Instance);
6: ucModule2.Instance.Dock = DockStyle.Fill;
7: ucModule3.Instance.BringToFront();
8: }
9: else
10: {
11: ucModule3.Instance.BringToFront();
12: }
13:
14: }
ucModule1 加入textBox1和timer1
程式碼加入
1:
2: private void ucModule1_Load(object sender, EventArgs e)
3: {
4: timer1.Enabled = true;
5: }
6:
7: private void timer1_Tick(object sender, EventArgs e)
8: {
9: this.textBox1.Text = string.Format("{0}", DateTime.Now.ToLongTimeString());
10: }
ucModule2 加入comboBox
ucModule2 中ComboBox1的內容
ucModule3 加入dateTimePicker
測試Module1按鈕
測試Module2按鈕
測試Module3按鈕
參考資料
1. C# Tutorial - Dynamically Loading User Control
全站熱搜
留言列表