c# 自定义事件传参(控件数据同步更新)

下面是传值的窗口代码

 

 public partial class Form1 : Form
    {
//自定义一个事件
public event EventHandler SetMsg; public Form1() { InitializeComponent(); Form2 form2 = new Form2(); SetMsg += form2.MainFormTxtChaned; form2.Show(); }
//这段代码是在控件初始化完成后把setMsg事件与form2里面的函数注册绑定在一起

 

//定义一个类继承与EventArgs
public class MyEventArg: EventArgs { public string Text { get; set; } }

窗体接收代码

internal void MainFormTxtChaned(object sender, EventArgs e)
        {
         
 //e就是A窗体传来的对象因为MyEventarg继承与EventArg所以可以强转类型
 MyEventArg arg = e as MyEventArg; this.SetText(arg.Text); }

数据传输窗口事件调用方式

  private void textBox1_TextChanged(object sender, EventArgs e)
        {
把这段代码放入textbox的changed事件就可以达到2个窗体上的textbox的内容就克同步更新了 SetMsg(
this, new MyEventArg() { Text = this.textBox1.Text }); }

 

猜你喜欢

转载自www.cnblogs.com/kangyuanjiang/p/9895762.html
今日推荐