窗体之间的传值方式(委托,事件参与)

父窗体代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace winform窗体之间的传值
{
    public partial class ParentFrm : Form
    {

        //定义发布信息委托

        public  Action<string> AfterInfo { get; set; }

        //定义消息发布的事件

        public event EventHandler AfterMsgChanges;
        //事件的触发只能在内部触发执行
        public ChildFrm childFrm { get; set; }
        public ParentFrm()
        {
            InitializeComponent();
        }
        

        
        private void btnParent_Click(object sender, EventArgs e)
        {
            #region   简单菜鸟传值方式

            //对象内部的属性,字段和元素不要直接访问
            //最好是通过方法来实现
            //第一种,垃圾代码实现
            //childFrm.txtChild.Text = this.txtParent.Text;
            //第二种  菜鸟实现
            //childFrm.SetText(this.txtParent.Text); 
            #endregion
            #region   委托传值方式
            //if (AfterInfo!=null)
            //{
            //    AfterInfo(this.txtParent.Text);
            //}
            //return;
            #endregion
            #region    触发事件方式

            AfterMsgChanges(this, new TextmsgChang() { Text = this.txtParent.Text });
            #endregion
        }

        private void ParentFrm_Load(object sender, EventArgs e)
        {
            ChildFrm child = new ChildFrm();
            childFrm = child;
            //子窗体弹出来之前,观察主窗体消息变化,有委托时调用
            // AfterInfo += child.SetText;//委托方式

            AfterMsgChanges += child.setparentPrm;//事件方式

            child.Show();
        }
    }
}

子窗体代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace winform窗体之间的传值
{
    public partial class ChildFrm : Form
    {
    //委托
        public   void   SetText(string txt)
        {
            this.txtChild.Text = txt;
        }
        public ChildFrm()
        {
            InitializeComponent();
        }
       //事件
        public void setparentPrm(object sender, EventArgs e)
        {
            //拿到父窗体传过来的值
            TextmsgChang erg = e as TextmsgChang;
            this.SetText(erg.Text);

        }
    }
}

调用事件类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace winform窗体之间的传值
{
  public  class TextmsgChang:EventArgs
    {
        public string Text { get; set; }
    }
}

多的就不说了,没说的太清楚,自己感兴趣,可以去看看实现过程,推理出来。
也可以留言。

最终实现效果:

在这里插入图片描述

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你的美,让我痴迷

你的好,我会永远记住你的。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值