从usercontrol访问表单
我有一个用户控件,需要访问Form1.cs上的变量和静态类。 我在谷歌上找不到一个有效的例子。 有什么提示吗? 谢谢!
namespace WinApp1 { public partial class Form1 : Form { Public MyCustomClass myClass; // need to access this public Form1() { } } public static class Global { public static myGlobalVar; // Need to Access This } }
在UserControl中使用this.Parent
来获取父窗体:
Form1 myParent = (Form1)this.Parent;
然后你可以访问公共领域/财产:
myParent.myClass
请注意,如果UserControl放置在Form中的Panel中,则需要获取父级的父级。
您可以通过其名称访问静态类:
Global.myGlobalVar
你可以使用FindForm()
但你应该退后一步,看看这是否是最好的解决方案。 这是一种强烈依赖性,会降低控件的可测试性和重用率。
例如,考虑引入一个接口,其中包含控件所需的成员,并在父hirachy中搜索它或将其作为参数注入,…
从那以后,您可以在我的情况下使用控件。 可能还有更多解决方案。 只是想让你想想,如果没有比依靠表格更好的东西..
使用 :
frm_main frm; //frm_main is your main form which user control is on it frm=(frm_main)this.FindForm(); //It finds the parent form and sets it to the frm
现在你有了主要表格。 frm的任何变化都将反映在主表格上。 如果要访问主窗体上的指定控件,请使用:
1 – 创建要访问的类型的控件(例如:标签):
Label lbl_main;
2 – 使用搜索结果中的返回控件设置标签:
frm.Controls.FindControl("controlId",true);
3 – 在标签上进行更改:
lbl_main.Text="new value changed by user control";
您的更改将反映在控件上。 希望有所帮助。
我以为this.Parent返回用户控件放置的实际页面? 然后您访问公共成员
在您的UserControl代码中,在Click事件或其他任何情况下:
private void sendParamToMainForm_Button_Click(object sender, EventArgs e) { mainForm wForm; wForm = (mainForm)this.FindForm(); wForm.lblRetrieveText.text = "whatever ..."; }
希望这可以帮助 :-)
上述就是C#学习教程:从usercontrol访问表单分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/992608.html