通过委托来实现
观察者模式
- 在父窗口定义委托
public Action <string> SendMsg{get;set;}
- 父窗口点击发送按钮
_Click(){
if(SendMsg==null){
return;
}
SendMsg(this.txtmsg.Text);
}
- 子窗体在弹出前,关注父窗体消息的变化
在子窗体中定义一个SetValue方法
public void SetValue(string txt){
this.msg.Text=txt;
}
父窗体中:
_Load(object sender){
ChildForm Child1=new ChildForm();
SendMsg+=Child1.SetValue;
}
事件方式传值
- 在父窗口定义事件
public event EventHandler/Action<string> SendMsgEvent{get;set;}
父窗体中:
_Load(object sender){
ChildForm Child1=new ChildForm();
SendMsgEvent+=Child1.SetValueEvent;
}
- 父窗口点击发送按钮
_Click(){
TextBoxMsgEventArg argtext=new TextBoxMsgEventArg();
argtext.Text=this.txtmsg.Text;
SendMsgEvent(this,argtext);
}
- 定义一个传递值的类
public class TextBoxMsgEventArg : EventArgs
{
public string Text {get; set;}
} - 在子窗体中定义一个SetValueEvent方法
public void SetValueEvent(object sender,EventArgs e){
TextBoxMsgEventArg arg= e as TextBoxMsgEventArg;
this.SetValue(arg.Text);
}
Ctrl+TAb键快速切换
事件与委托的区别
- 委托是一个类型,事件是委托的一个实例
- 事件只能在类的内部触发
非委托方式
设置一个集合,放置所有需要关注父窗口消息变化的子窗口
父窗口定义一个集合
public List<IChildForm> ChildFormList{get;set;}
_Click(){
foreach(var item in ChildFormList){
item.SetText(this.txtMsg.Text);
}
}
_Load(){
// Child chid=new Child();
// this.ChildFormList=new List<IChildForm>();
// this.ChildFormList.Add(chid);
// chid.show();
}
- 接口类IChildForm
public Interface IChildForm{
void setText(string txt);
}
- 子窗体
Child: Form,IChildForm
{
public void setText(string txt){
this.txtMsg.Text=txt;
}
}
为了让父窗口与子窗口解耦,可以在添加一个总窗口
Master_Load(){
MainForm mform=new MainForm();
ChildForm cform =new ChildForm();
mform.ChildFormList=new List<IChildForm>();
mform.ChildFormList.Add(cform);
mform.show();
cform.show();
}