Winform窗体之间传值

通过委托来实现

观察者模式

  • 在父窗口定义委托
 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();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值