用委託來實現子表單操作父表單中的控制項

來源:互聯網
上載者:User

代碼實現
Form1中,一個Lable1;在Form2中控制Form1中的Lable1的顯示或隱藏!
Form1代碼:

view plaincopy to clipboardprint?

  1. namespace WindowsApplication2  
  2. {  
  3. public delegate void SetVisiableHandler();  
  4. public partial class Form1 : Form  
  5.     {  
  6. public Form1()  
  7.         {  
  8.             InitializeComponent();  
  9.         }  
  10. private void button1_Click(object sender, EventArgs e)  
  11.         {  
  12.             Form2 frm = new Form2(new SetVisiableHandler(SetVisiable));  
  13.             frm.Show();  
  14.         }  
  15. private void SetVisiable()  
  16.         {  
  17.             SetVisiable(this.label1, !this.label1.Visible);  
  18.         }  
  19. private void SetVisiable(Control control, bool visiable)  
  20.         {  
  21. if (this.Controls.Contains(control))  
  22.             {  
  23.                 control.Visible = visiable;  
  24.             }  
  25.         }  
  26.     }  

namespace WindowsApplication2 { public delegate void SetVisiableHandler(); public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form2 frm = new Form2(new SetVisiableHandler(SetVisiable)); frm.Show(); } private void SetVisiable() { SetVisiable(this.label1, !this.label1.Visible); } private void SetVisiable(Control control, bool visiable) { if (this.Controls.Contains(control)) { control.Visible = visiable; } } } }

Form2代碼

view plaincopy to clipboardprint?

  1. namespace WindowsApplication2  
  2. {  
  3. public partial class Form2 : Form    {  
  4. private SetVisiableHandler m_setVisible;  
  5. public Form2(SetVisiableHandler setvisible)  
  6.         {  
  7.             InitializeComponent();  
  8. this.m_setVisible = setvisible;  
  9.         }  
  10. private void btnVisible_Click(object sender, EventArgs e)  
  11.         {  
  12. if (this.m_setVisible != null)  
  13.             {  
  14. this.m_setVisible();  
  15.             }  
  16.         }  
  17.     }  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.