使用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的值");
        }
    }
}

 

posted @ 2012-06-21 16:09  MagiCube  阅读(518)  评论(0编辑  收藏  举报