Access Form controls from static class [duplicate]

怎甘沉沦 提交于 2019-12-02 18:35:56

问题


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.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/24397255/access-form-controls-from-static-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!