从usercontrol访问表单

问题描述 投票:2回答:6

我有一个用户控件,需要访问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
}
}
c# user-controls
6个回答
6
投票

在UserControl中使用this.Parent来获取父表单:

Form1 myParent = (Form1)this.Parent;

然后你可以访问公共领域/财产:

myParent.myClass 

请注意,如果UserControl放置在Form中的Panel中,则需要获取父级的父级。

您可以通过其名称访问静态类:

Global.myGlobalVar 

4
投票

你可以使用FindForm()

但是你应该退后一步,看看这是否是最好的解决方案。这是一种强烈的依赖性​​,会降低控件的可测试性和重用率。

例如,考虑引入一个接口,其中包含控件所需的成员,并在父hirachy中搜索它或将其作为参数注入,...

从那以后,您可以在我的情况下使用控件。可能还有更多解决方案。只是想让你想想,如果没有比依靠表格更好的东西..


2
投票

使用 :

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";

您的更改将反映在控件上。希望有所帮助。


1
投票

我以为this.Parent返回用户控件放置的实际页面?然后你访问公共成员


0
投票

在您的UserControl代码中,在Click事件或其他任何情况下:

private void sendParamToMainForm_Button_Click(object sender, EventArgs e)
{
    mainForm wForm;
    wForm = (mainForm)this.FindForm();

    wForm.lblRetrieveText.text = "whatever ...";
}

希望这可以帮助 :-)


0
投票

如果您的用户控件位于面板内,并且您想要访问该表单 您可以使用

        Main_Form myform = (Main_Form)ParentForm;
        MessageBox.Show(myform.Label2.Text);
© www.soinside.com 2019 - 2024. All rights reserved.