例如有下面的需求需要实现:程序主画面中弹出一个子窗口。此时主画面仍然可以接收用户的操作(子窗口是非模态的)。子窗口上进行某些操作,根据操作的结果要在主画面上显示不同的数据。
即如下图所示:
大多数我们会这样做:
表单1窗口定义:
class="code_img_closed" src="/Upload/Images/2013110711/0015B68B3C38AA5B.gif" alt="" />logs_code_hide('0d968b5f-4c59-4124-b660-b08f28ca616a',event)" src="/Upload/Images/2013110711/2B1B950FA3DF188F.gif" alt="" />1 public partial class Form1 : Form 2 { 3 4 public string LabelName 5 { 6 get { return this.label1.Text; } 7 set { this.label1.Text = value; } 8 } 9 10 public Form1() 11 { 12 InitializeComponent(); 13 this.button1.Click += new EventHandler(button1_Click); 14 } 15 16 /// <summary> 17 /// 按钮触发 18 /// </summary> 19 /// <param name="sender"></param> 20 /// <param name="e"></param> 21 private void button1_Click(object sender, EventArgs e) 22 { 23 Form2 form2 = new Form2(); 24 form2.form1 = this; 25 form2.Show(); 26 } 27 }View Code
表单2窗口定义:
1 public partial class Form2 : Form 2 { 3 public Form1 form1; 4 public Form2() 5 { 6 InitializeComponent(); 7 this.button1.Click += new EventHandler(button1_Click); 8 } 9 10 /// <summary> 11 /// 表单2按钮触发 12 /// </summary> 13 /// <param name="sender"></param> 14 /// <param name="e"></param> 15 private void button1_Click(object sender, EventArgs e) 16 { 17 form1.LabelName = "改变之后"; 18 } 19 }View Code
这样虽然可以达到目的,但是各个模块之间产生了很强的耦合。一般说来模块之间的调用应该是单方向的:模块A调用了模块B,模块B就不应该反向调用A,否则就破坏了程序的层次,加强了耦合程度,也使得功能的改变和追加变得很困难。
所以这里就用到了事件:
下边是表单2中的事件定义:
1 public partial class Form2 : Form 2 { 3 public delegate void OutputMessage(object sender, System.EventArgs e); 4 public event OutputMessage ButtonClick; 5 6 public Form2() 7 { 8 InitializeComponent(); 9 this.button1.Click += new EventHandler(button1_Click); 10 } 11 12 /// <summary> 13 /// 表单2按钮触发 14 /// </summary> 15 /// <param name="sender"></param> 16 /// <param name="e"></param> 17 private void button1_Click(object sender, EventArgs e) 18 { 19 ButtonClick(this, e); 20 } 21 }
然后在表单1中进行捕获:
1 public partial class Form1 : Form 2 { 3 public Form1() 4 { 5 InitializeComponent(); 6 this.button1.Click += new EventHandler(button1_Click); 7 } 8 9 /// <summary> 10 /// 按钮触发 11 /// </summary> 12 /// <param name="sender"></param> 13 /// <param name="e"></param> 14 private void button1_Click(object sender, EventArgs e) 15 { 16 Form2 form = new Form2(); 17 form.Show(); 18 form.ButtonClick += new Form2.OutputMessage(form_ClickButton); 19 } 20 21 private void form_ClickButton(object sender, EventArgs e) 22 { 23 this.label1.Text = "改变之后"; 24 } 25 }
这样,各个模块专心的做自己的事情,不需要过问其他模块的事情。
不知道说的对不对,还请指教。。。