窗体传值发布订阅模式(委托版)

1.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 WindowsFormsApplication16
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public event Action<string> FuncAction;


        private void Form1_Load(object sender, EventArgs e)
        {
          
        }

        private void button1_Click(object sender, EventArgs e)
        {

            if (FuncAction == null) return;
            
            FuncAction(textBox1.Text);//在管理窗体往该委托或者事件上注册方法,如果委托或者事件不为空,则执行该委托或事件
//委托的原理包含三部分 target ,methodptr,委托数组 (继承自多播委托)
//执行委托会执行在该委托或者事件注册的方法
//委托和事件的区别,事件只能在类内部执行,而委托可以在外部注册执行,相比之下没有事件安全, 事件不能赋值方法指针,只能+=和-=,而委托还可以用等号赋值。         
           

        }
    }
}
2.Form2和Form3都是如此的代码
namespace WindowsFormsApplication16
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        public void setText(string msg)
        {
            textBox1.Text = msg;
        }

      
    }
}
3.Form4管理窗体

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 WindowsFormsApplication16
{
    public partial class Form4 : Form
    {
        public Form4()
        {
            InitializeComponent();
        }

        private void Form4_Load(object sender, EventArgs e)
        {
            Form1 f1=new Form1();
            Form2 f2=new Form2();
            Form3 f3=new Form3();
            f1.FuncAction += f2.setText;//想要关注Form1的变化就注册方法到该事件或委托上
            f1.FuncAction += f3.setText;//想要关注Form1的变化就注册方法到该事件或委托上
         
             f1.Show();
            f2.Show();
            f3.Show();
        }
    }
}

原文地址:https://www.cnblogs.com/kexb/p/4474574.html