使用Delegate传递父子窗口数据

在winform程序开发过程中,有时会用到子窗口向父窗口传递数据的情况,比如:我点了一个修改信息的按钮,弹出一个具体信息的子窗口,我们在该子窗口完成信息的修改,这时父窗口的数据应该得到更新,当然有多种方法来处理这种情况,但是处理这种情况最好的应该是使用Delegate。

首先,我们在子窗口声明我们的代理:

public delegate void SetMainTextBoxValueDelegate(string strValue);

 这样一个接收父窗口方法的代理就声明好了,当然为了更好的使用代理,我们声明一个事件:

public event SetMainTextBoxValueDelegate SetMainTextBoxValue;

 这样主程序就可以使用通过事件来注册使用该代理函数了。在父窗口注册该事件之前,我们在子窗口修改数据的地方,调用该代理:

private void subButton_Click(object sender, EventArgs e)
        {
            SetMainTextBoxValue("设置主窗体TextBox的值");
        }

 现在可以再父窗体中注册该事件了:

subForm.SetMainTextBoxValue += new SetMainTextBoxValueDelegate(subForm_SetMainTextBoxValue);

 同时声明事件处理函数:

void subForm_SetMainTextBoxValue(string strValue)
        {
            textBoxMain.Text = strValue;
        }

  这样就可以实现在子窗口修改数据,同时父窗口数据也跟着更新。

父窗口完整代码:

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

        private void Pop_Click(object sender, EventArgs e)
        {
            SubForm subForm = new SubForm();
            subForm.SetMainTextBoxValue += new SetMainTextBoxValueDelegate(subForm_SetMainTextBoxValue);
            subForm.ShowDialog();
        }

        void subForm_SetMainTextBoxValue(string strValue)
        {
            textBoxMain.Text = strValue;
        }
    }
}

 子窗口完整代码:

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 DelegateExample
{
    public delegate void SetMainTextBoxValueDelegate(string strValue);
    public partial class SubForm : Form
    {
        public event SetMainTextBoxValueDelegate SetMainTextBoxValue;

        public SubForm()
        {
            InitializeComponent();
        }

        private void subButton_Click(object sender, EventArgs e)
        {
            SetMainTextBoxValue("设置主窗体TextBox的值");
        }
    }
}

 

转载于:https://www.cnblogs.com/magic-cube/archive/2012/06/21/2557896.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值