从静态类访问表单控件 [英] Access Form controls from static class

查看:46
本文介绍了从静态类访问表单控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有很多控件的Form1,我需要访问/编辑另一个静态类中的控件值.由于我在表单上有很多控件,因此需要花费一些时间来定义set并从中获取控件.我想知道是否有什么方法可以在静态类中定义Form1的实例,以便可以访问此类中的Form1的所有控件?

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?

这是静态类的结构:

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.

推荐答案

您可以以静态形式声明:

You can declare in the static form:

private static MyformType myform;

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

虽然,这个概念通常不太好,也许更好的方法是将您的形式作为参数传递给在静态类中调用的函数,并通过属性框中的chanign acces修饰符将您应该控制的控制权公开表格

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

这篇关于从静态类访问表单控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆