Winform編程中經常會用到Form與Form之間傳遞參數或者Form1中的動作更新Form2中的數據或呈現,網路中也有很多大師寫過類似的文章,本文不是想重提來說明什麼,只是分享一下自己的實現和一些想法。
先說實現好了:
Step1:定義一個ParentChildRelateEventHandler<TEventArgs>和一個自定義EventArgs
定義一個ParentChildRelateEventHandler<TEventArgs>目的是一個項目中可能會有多處此類的處理,那通過範型實現一個delegate模板,就不需要每個地方都重新定義一遍了;
定義一個EventArgs的目的是Form之間傳遞的可能是自定義對象,所以,需要提供一個EventArgs的模板供調用時指定特定的對象類型;
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