窗体
是Form类对象,Control类的子类
实验步骤
- 通过父窗体打开子窗体
- 父窗体向子窗体传值:static变量 、重写构造函数
- 子窗体向父窗体传值:委托、Owner属性
static变量传值
子窗:
namespace psssv
{
public partial class Child : Form
{
public Child()
{
InitializeComponent();
tChid.Text=temp.s;
}
public class temp
{
public static string s = "";
}
}
注意temp类声明不能在Child前面,不然会报错,因为Child是Partial类。
父窗:
namespace psssv
{
public partial class Parent : Form
{
public Parent()
{
InitializeComponent();
}
private void bParent_Click(object sender, EventArgs e)
{
Child c = new Child();
//static变量:
temp.s = tParent.Text;
c.ShowDialog();
}
}
}
- 特点:双向传值,操作简单
- 缺点:不安全。static变量在类加载时就分配内存,一般不会被销毁,除非系统内存不够,static变量才会被回收,导致静态变量访问错误
通过重写构造函数传值
子窗:
namespace psssv
{
public partial class Child : Form
{
public Child(string s)
{
InitializeComponent();
tChid.Text = s;
}
}
父窗:
namespace psssv
{
public partial class Parent : Form
{
public Parent()
{
InitializeComponent();
}
private void bParent_Click(object sender, EventArgs e)
{
Child c = new Child(tParent.Text);
c.ShowDialog();
}
}
}
通过委托传值
委托:指向签名、返回类型相同的一组有序方法的指针
特点:适用于子窗体向父窗体传值,解耦
步骤:
- 声明委托
- 声明事件
- 编写事件处理方法
- 注册事件
- 触发事件
子窗:
namespace psssv
{
//声明委托
public delegate void mdel(string s);
public partial class Child : Form
{
//声明事件
public event mdel m;
public Child()
{
InitializeComponent();
}
private void bChild_Click(object sender, EventArgs e)
{
//触发事件
m(tChid.Text);
}
}
父窗:
namespace psssv
{
public partial class Parent : Form
{
public Parent()
{
InitializeComponent();
}
private void bParent_Click(object sender, EventArgs e)
{
Child c = new Child();
//注册事件
c.m += ctext;
c.ShowDialog();
}
private void ctext(string s)//事件处理方法
{
tParent.Text = s;
}
}
}
通过Owner属性传值
Owner:拥有此窗体的窗体
步骤:
- 声明Owner
- 获取拥有此窗体的窗体
- 获取包含在控件p的控件集合中的tParent属性:
子窗:
namespace psssv
{
public partial class Child : Form
{
public Child()
{
InitializeComponent();
}
private void bChild_Click(object sender, EventArgs e)
{
//Owner属性:
Parent p = new Parent();
p = (Parent) this.Owner;
p.Controls["tParent"].Text = tChid.Text;
}
}
父窗:
namespace psssv
{
public partial class Parent : Form
{
public Parent()
{
InitializeComponent();
}
private void bParent_Click(object sender, EventArgs e)
{
Child c = new Child();
//Owner属性:
c.Owner = this;
c.ShowDialog();
}
}
}