用委托来实现子窗体操作父窗体中的控件

代码实现
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.     }  

posted on 2010-09-28 16:51  风雨者2  阅读(305)  评论(0编辑  收藏  举报

导航