通过系统自带的事件传值
public event EventHandler SendMsgEvent;//使用默认的事件处理委托
Form2 f2=new Form();
SendMsgEvent+=f2.MainFormTxtChaed;//为子窗体注册事件
f2.Show();
SendMsgEvent(this,new MyEventArg(){Text=this.txtMsg.Text});
internal void MainFormTxtChaned(object Sender,EventArgs e){
MyEventArg arg=e as MyEventArg;
this.SetText(arg.Text);
}
public void SetText(string txt)
{
this.txtMsg.Text = txt;
}
public void AfterParentFrmTextChange(object sender, EventArgs e)
{
//拿到父窗体的传来的文本
MyEventArg arg = e as MyEventArg;
this.SetText(arg.Text);
}
通过保存对象的引用调用的对象的公有方法实现窗体的传值
public ObeserverFormA ChildFormA { get; set; }
public ObeserverFormB ChildFormB { get; set; }
ObeserverFormA childFormA = new ObeserverFormA();
ChildFormA = childFormA;
childFormA.Show();
ObeserverFormB childFormB = new ObeserverFormB();
ChildFormB = childFormB;
childFormB.Show();
ChildFormA.SetText(this.txtMsg.Text);
ChildFormB.SetText(this.txtMsg.Text);
定义发布消息的委托 委托是一个类型 委托可以在外部获得执行
public Action<string> SendMsg { get; set; }
ObeserverFormA childFormA = new ObeserverFormA();
SendMsg += childFormA.SetText;//委托赋值
childFormA.Show();
ObeserverFormB childFormB = new ObeserverFormB();
SendMsg += childFormB.SetText;
childFormB.Show();
if (SendMsg!=null)
{
SendMsg(this.txtMsg.Text);//执行所有注册的委托
}
链接:https://pan.baidu.com/s/114V3u7GYEtDbWYkf0fSjyg
提取码:no94