基于父页面的函数调用用户控件 [英] function call user control based on the parent pag
问题描述
我在Windows窗体应用程序中有一个用户控件,我需要基于父窗体调用diffrene methode,我的控件有两个父窗体......
我该怎么做才能帮助我
i have a user control in windows form application i need to raise diffrene methode based on the the parent form called my control have two parent form...........
how can i do pls help me
推荐答案
Don''t.相反,您可以采用另一种方式:在您的子表单中创建一个事件,父表单会订阅该事件.这样,孩子就不需要知道有关父母的存在的任何信息,它只是表示我有数据!".如果有兴趣,则父级将按要求进行处理.
在子窗体中:
Don''t. Instead, do it the other way: create an event in your child form, which the parent form subscribes to. That way, the child does not need to know anything about the existence of the parent - it just signals "I have data!" and the parent will process it as required if it is interested.
In the child form:
public partial class frmChild : Form
{
// Signal data change happened
public event EventHandler Changed;
protected virtual void OnChanged(EventArgs e)
{
EventHandler eh = Changed;
if (eh != null)
{
eh(this, e);
}
}
private void DoSomethingToChangeData()
{
OnChanged(null);
}
}
-----给eh的指示是如果处理程序在空检查之间进行更改
-----和执行.
-----(不太可能,但可能)
-----空检查是为了确保有处理程序.如果不是,最好
-----优雅地忽略它,而不是依靠抛出的异常
-----(NullReferenceException)
在家长表格中:
----- The asign to eh is in case the handler changes between null check
----- and exec.
----- (unlikely, but possible)
----- The null check is to ensure there is a handler. If not, better to
----- ignore it gracefully, than to rely on the thrown exception
----- (NullReferenceException)
In the Parent form:
private void ShowChildForm()
{
// Link in his event so if it changes, we detect it.
frmChild fd = new frmChild();
fd.Change += new frmChange.ChangeHandler(Changed);
fd.ShowDialog();
}
//
// Fired when the data is changed at a lower level.
//
private void Changed(object sender, EventArgs e)
{
}
在common文件中保留一个静态变量(ParentName),例如common.cs
例子
公共静态字符串ParentName =";
在父级form1的Form_Load事件中
Keep One Static Variable (ParentName) in Common File like common.cs
Example
Public static string ParentName="";
On Form_Load event of your parent form1
Common.ParentName="Form1";
在父级form2的Form_Load事件中
On Form_Load event of your parent form2
Common.ParentName="Form2";
在Usercontrol中,在调用方法之前,请检查
开关(Common.ParentName)
{
案例"Form1":
//调用Method1;
休息;
案例"Form2":
调用Method1;
休息;
}
希望这会有所帮助!
In Usercontrol Before calling a method check
switch(Common.ParentName)
{
case "Form1":
//Call Method1;
break;
Case "Form2":
Call Method1;
break;
}
Hope this helps!
这篇关于基于父页面的函数调用用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!