从用户控件访问表单 [英] access form from usercontrol
本文介绍了从用户控件访问表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个用户控件,该控件需要访问Form1.cs上的变量和静态类。我在Google上找不到有效的示例。有什么提示吗?
I have a user control, that needs to access variables and static classes on Form1.cs. I can't find a working example on google. Any hints please? Thanks!
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
获取父表单:
Use this.Parent
in UserControl to get the parent form :
Form1 myParent = (Form1)this.Parent;
然后您可以访问公共字段/属性:
then you can access the public field/property :
myParent.myClass
请注意,如果UserControl放在窗体内的面板中,您需要获取父级的父级。
Note that if the UserControl is placed in a Panel inside the Form, you will need to get parent of parent.
您可以通过其名称访问静态类:
You can access the static class by its name :
Global.myGlobalVar
这篇关于从用户控件访问表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文