winform利用委托实现窗体间传值
Form1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace FormTransMessage
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
//4、注册form2_MyEvent方法的MyEvent事件
form2.MyEvent += new MyDelegate(form2_MyEvent);
form2.Show();
}
/// <summary>
/// form2要求form1中要实现的事件
/// </summary>
void form2_MyEvent()
{
this.label1.Text = "证明确实是!";
}
private void Form1_Load(object sender, EventArgs e)
{
this.label1.Text = "我是天才!";
}
}
}
Form2:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace FormTransMessage
{
//1、定义一个委托
public delegate void MyDelegate();
public partial class Form2 : Form
{
//2、定义该委托的事件
public event MyDelegate MyEvent;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//3、触发事件的地方
MyEvent();
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
Form3 form = new Form3();
form.myevent += new Mydelegate(form3_event);
form.Show();
}
void form3_event()
{
this.button2.Enabled = false;
}
}
}
总结:利用委托来实现窗体间传值遵循如下几步即可:
1、在弹出窗体中定义委托,并定义委托的一个事件,明确触发该事件的地方;
2、在父窗体中定义相应的方法,并在实例化弹出窗体时注册该方法给弹出窗体中的事件。