功能实现:当子窗口中文本内容变化时,主窗体显示内容随之改变。
主窗体代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 委托应用从窗体向主窗体发送信息
{
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
Frm1 frm1 = new Frm1();
//将子窗体的委托变量和主窗体的对应方法关联
frm1.countShow = this.Reader;
frm1.Show();
}
/// <summary>
/// 第二步:根据委托创建一个方法,接收委托传递的信息
/// </summary>
/// <param name="count"></param>
private void Reader(string count)
{
this.lbl_ReadCount.Text = count;
}
private void FrmMain_Load(object sender, EventArgs e)
{
}
}
//第一步:声明委托(定义在类的外边),因为想接收的是textBox的内容,此处参数类型为string
public delegate void CountShow(string count);
}
子窗体代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 委托应用从窗体向主窗体发送信息
{
public partial class Frm1 : Form
{
public Frm1()
{
InitializeComponent();
}
//第三步:根据委托创建委托对象
public CountShow countShow;
private void textBox1_TextChanged(object sender, EventArgs e)
{
if(countShow != null)
{
countShow(textBox1.Text);
}
}
}
}