Form之间传递参数或联动的范型代理实现

本文介绍了一种Winform编程中父窗体与子窗体间高效通信的方法,利用自定义事件委托实现参数传递与数据更新,提高了组件的复用性和灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    Winform编程中经常会用到Form与Form之间传递参数或者Form1中的动作更新Form2中的数据或呈现,网路中也有很多大师写过类似的文章,本文不是想重提来说明什么,只是分享一下自己的实现和一些想法。

    先说实现好了:

    Step1:定义一个ParentChildRelateEventHandler<TEventArgs>和一个自定义EventArgs
    定义一个ParentChildRelateEventHandler<TEventArgs>目的是一个项目中可能会有多处此类的处理,那通过范型实现一个delegate模板,就不需要每个地方都重新定义一遍了;
    定义一个EventArgs的目的是Form之间传递的可能是自定义对象,所以,需要提供一个EventArgs的模板供调用时指定特定的对象类型;

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

namespace  TestForDelegate
{
    
/// <summary>
    
///  This event handler is for the relation event of parent form and child form
    
/// </summary>
    
/// <typeparam name="TEventArgs">the event arges you want to tell the event handler</typeparam>
    
/// <param name="sender">the object who fired this event</param>
    
/// <param name="e">the event arges</param>

    public delegate void ParentChildRelateEventHandler<TEventArgs>(object sender, TEventArgs e)
        
where TEventArgs : EventArgs;

    
/// <summary>
    
///  This event args is for the relation of parent form and child form
    
/// </summary>
    
/// <typeparam name="TType">The type that you want to tell the args to transfer</typeparam>

    public class ParentChildRelateEventArgs<TType> : EventArgs
    
{
        
/// <summary>
        
///  Contructor of ParentChildRelateEventArgs
        
/// </summary>
        
/// <param name="t">the Type you want to transfer</param>

        public ParentChildRelateEventArgs(TType t)
        
{
            
this.m_CustomObject = t;
        }


        
private TType m_CustomObject;
        
/// <summary>
        
///  Get or Set the object that can make you transfer it between parent form and child form
        
/// </summary>

        public TType CustomObject
        
{
            
get return m_CustomObject; }
            
set { m_CustomObject = value; }
        }

    }

}

    Step2:FormChild中暴露事件供FormParent调用

   

    Step3:Parent Form中ShowDialog调用ChildForm,并对ChildForm的事件进行实现动作

   

    这样就完成了ParentForm和ChildForm之间的对话。

    优点:Child Form和Parent Form之间解除了关联关系,故Child Form可以不依赖于Parent Form而存在,从而可以将Child Form发布成为共用的组件以便重用;采用范型实现代理和EventArgs,灵活性提高,同一个Project或多个Project都可以公用一份;EventHandler也采用范型实现,可以供使用者使用自定义的EventArgs来实现更复杂的需求;

    缺点:其实也谈不上缺点了,就是觉得不长写的人看着可能晕~呵呵

附:测试代码Solution
Download

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值