非委托/利用委托
网上搜索的关于C#的文章多得不胜枚举,但没有一篇是实用的,本人的实实在在绝对能运行,解决父子窗口通信问题,mdi窗口问题,而且简单易懂.......
《1》
我们这里假设已经存在了两个窗体分别为:FormFather(父窗体)(父窗体的IsMdiContainter要设置为true)和FormChild(子窗体),而父窗体中有一个名为Btn_OpenChild的按钮,用来打开子窗体,子窗体中也有个名为Btn_IsTrue按钮和一个TextBox控件。当TextBox控件中输入“True”时,父窗体的Btn_OpenChild可用,并关闭子窗体,当输入其它任何字符或字符串父窗体的Btn_OpenChild都不可用而不关闭子窗体,当然刚启动程序时的父窗体的Btn_OpenChild按钮是可用的。下面是实现的代码:
1//下面是主窗体的代码
2using System;
3using System.Collections.Generic;
4using System.ComponentModel;
5using System.Data;
6using System.Drawing;
7using System.Text;
8using System.Windows.Forms;
9
10namespace MDIFormDemo
11{
12 public partial class FormFather : Form
13 {
14 public FormFather()
15 {
16 InitializeComponent();
17 }
18
19 private void OpenChild()//在MDI父窗体中显示子窗体
20 {
21 foreach (Form f in this.MdiChildren)
22 {
23 if ((f) is FormChild)
24 {
25 f.Activate();
26 return;
27 }
28 }
29 FormChild frm = new FormChild(this);
30 frm.MdiParent = this;
31 frm.Show();
32 }
33
34 private void FormFather_Load(object sender, EventArgs e)
35 {
36 OpenChild();//父窗体被打开时,子窗体也同时被打开
37 }
38 private void Btn_OpenChild_Click(object sender, EventArgs
e)
39 {
40 OpenChild();//如果Btn_OpenChild可用,则点击此按钮也能打开子窗体
41 }
42}主窗体中没有什么特别的,只是注意第29行的代码中的“this”,接合子窗体的代码你就能明白为何要加上这个“this”了(平时只为了打开子窗体时,我们都不会需要在括号中输入“this”)。
//下面是子窗体的代码
1using System;
2using System.Collections.Generic;
3using System.ComponentModel;
4using System.Data;
5using System.Drawing;
6using System.Text;
7using System.Windows.Forms;
8
9namespace MDIFormDemo
10{
11 public partial class FormChild : Form
12 {
13 private FormFather MyForm;
14 public FormChild (FormFather f)
15 {
16 InitializeComponent();
17 MyForm = f;
18 }
19
20 private void FormChild_Load(object sender, EventArgs e)
21 {
22
23 }
24
25 private void Btn_IsTrue_Click(object sender, EventArgs e)
26 {
27 if (this.textBox1.text == "True")
28 {
29 MyForm.Btn_OpenChild.Enabled = true;
30 this.Close();
31 }
32 else
33 {
34 MyForm.Btn_OpenChild.Enabled = false;
35 }
36 }
37}
《2》
用委托来实现用观察者模式
1. 在FormFather类里定义一个方法private void DisableMenu(bool flag)
2. FormChild类里定义一个委托
public delegate void InputTrueHandler(bool flag);
public InputTrueHandler MyHandler;
3.
在OpenChild()方法里实例化FormChild后将DisableMenu方法注册到实例化后的FormChild对象的InputTrueHandler类型委托MyHandler上
FormChild frm = new FormChild();
frm.MdiParent = this;
frm.MyHandler+= new FormChild.InputTrueHandler(DisableMenu)
frm.Show();
4. Btn_IsTrue_Click改为如下:
private void Btn_IsTrue_Click(object sender, EventArgs e)
{
if (this.textBox1.text == "True")
{
if(MyHandler!=null)
MyHandler(true);
this.Close();
}
else
{
if(MyHandler!=null)
MyHandler(false);
}
}
这样子窗体就不用知道父窗体的存在,从而解除2个窗体间的偶合,让子窗体复用性更高