C# 动态创建出来的窗体间的通讯 delegate1

本文介绍如何通过委托实现窗体之间的数据传递,确保每个窗体独立且可重复利用,具体展示了Form1和Form2如何通过委托共享数据。

附件 http://files.cnblogs.com/xe2011/CSharp_WindowsForms_delegate01.rar

 

需要每个窗体是独立存在,禁止相与引用窗体

这样干净并且可以反复重用

 

 

Form1的代码

      private void button1_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2();
            f2.XYZ += new Form2.CallBack(GetForm2TextBox1Text);
            f2.Show();
        }

        void GetForm2TextBox1Text(string s)
        {
            textBox1.Text = s;
        }

 

Form2

        public delegate void CallBack(string s);
        public event CallBack XYZ;
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            XYZ(textBox1.Text);
        }

 

 

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

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2();
            f2.XYZ += new Form2.CallBack(GetForm2TextBox1Text);
            f2.Show();
        }

        void GetForm2TextBox1Text(string s)
        {
            textBox1.Text = s;
        }

    }
}
Form1

 

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

        public delegate void CallBack(string s);
        public event CallBack XYZ;
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            XYZ(textBox1.Text);
        }

    }
}
Form2

 

 

 

转载于:https://www.cnblogs.com/xe2011/p/3440258.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值