Access Form controls from static class [duplicate]

2019-03-04 12:44发布

This question already has an answer here:

I have a Form1 with lots of controls and I need to access/edit control values from another static class. Since I have lots of controls on the form, it takes some time to define set and get from every single of them. I am wondering if there is any way that I can define an instance of the Form1 within the static class so that I can have access to all controls of Form1 in this class?

Here is the structure of the static class:

public static class Glob
{
    public static int int1;

    public static int Func1()
    {
        return 10;
    }
}

I am using static class with static methods and variables as I need to be able to easily access its variables and methods from any other form and class. This way I do not need to define an instance of the class every single time I need to call them. Also, by help of static class, I can share variables between classes and forms.

2条回答
别忘想泡老子
2楼-- · 2019-03-04 12:51

You can apply singleton pattern to your form. Note that Instance will return reference to last created instance of MyForm, so you shouldn't have more than one instance of MyForm out there.

Backing field:

    private static MyForm _instance

Singleton accessor:

    public static MyForm Instance
    {
        get
        {
            return _instance;
        }
    }

Once you beging using the class, you can assign its reference to the backing field

    public MyForm()
    {
        _instance = this;
    }

As a side note; if you have a choice of technologies, check out WPF. It has bindings to programmatically get and set values of UI controls at

查看更多
干净又极端
3楼-- · 2019-03-04 13:09

You can declare in the static form:

private static MyformType myform;

public static void setmyform(MyformType myform1)
{
  myform=myform1;
}

although, that concept generally isn't so good, maybe better way would be passing your form as argument to functions called in the static class, and make your contorl which should be accesed public, by chanign acces modifier in propertis box of the form

public static void EgClearText(Textbox tb)
{
  tb.Text="";
}
public static void DoSomethingElseWithTheForm(MyformType myform)
{
  myform.someOtherContol.Visible=false;
}
查看更多
登录 后发表回答