委托实现和事件实现
public partial class ParentForm : Form
{
public ParentForm()
{
InitializeComponent();
ChildForm childForm = new ChildForm();
//注册方法
SetTextDel += childForm.SetText;
EventChildForm eventChildForm = new EventChildForm();
//注册事件
TxtMsgChangeHandler += eventChildForm.ParentTxtMsgChangeHandler;
eventChildForm.Show();
childForm.Show();
}
//定义一个委托属性
private Action<string> SetTextDel { get; set; }
//定义一个textbox的text改变的事件
private event EventHandler TxtMsgChangeHandler;
private void btnSendMsg_Click(object sender, EventArgs e)
{
if(SetTextDel==null)
{
return;
}
//执行委托
SetTextDel(txtMsg.Text);
//触发事件
TxtMsgChangeHandler(this, new EventArgTxtChange() { Text = this.txtMsg.Text });
}
}
public partial class ChildForm : Form
{
public ChildForm()
{
InitializeComponent();
}
public void SetText(string text)
{
txtMsg.Text = text;
}
}
public partial class EventChildForm : Form
{
public EventChildForm()
{
InitializeComponent();
}
public void ParentTxtMsgChangeHandler(object sender, EventArgs e)
{
EventArgTxtChange eTxtChange = e as EventArgTxtChange;
txtMsg.Text = eTxtChange.Text;
}
}
public class EventArgTxtChange:EventArgs
{
public string Text { get; set; }
}