简体   繁体   English

如何从其他窗体访问一个窗口窗体中的控件

[英]How to access a control in one window form from other form

Sir, I have two window forms, each form has some controls. 先生,我有两个窗口形式,每个窗体都有一些控件。 I want to access control of one form from another form. 我想从另一个表单访问一个表单的控件。 I have tried two ways- 1- Make controls public and access them. 我尝试了两种方法 - 1-将控件公开并访问它们。 2- Make public properties getting and setting control according to requirement. 2-根据需要进行公共属性获取和设置控制。 But in both the case i have to create the object of first form in order to access the properties or public control. 但在这两种情况下我都必须创建第一个表单的对象才能访问属性或公共控件。 I have instaintiated a socket object and bind it to the local endpoint in the constructor of the first form. 我已经实现了一个套接字对象并将其绑定到第一个表单的构造函数中的本地端点。 Now if I create another object of first form in order to access the control, constructor is fired again and the same code of socket binding in executed which results an exception. 现在,如果我为了访问控件而创建了第一个表单的另一个对象,则会再次触发构造函数并执行相同的套接字绑定代码,从而导致异常。 Please suggest me what to do ??? 请建议我做什么??? Thankssssss.... Thankssssss ....

You can do this in many ways... 你可以用很多方式做到这一点......

You can declare some static getter/setter to manage a static instance of the compononent: 您可以声明一些静态getter / setter来管理组件的静态实例:

private static Type _myObject;
public static Type MyObject
{
   get
   {
      return _myObject;
   }
}

In this case you can access it from evrywere if you only need a specific shared object 在这种情况下,如果您只需要特定的共享对象,则可以从evrywere访问它

MyClass.MyObject.Function();

Or you can define a getter for the whole class: 或者您可以为整个类定义一个getter:

public class MyClass
{
   static MyClass _myClass;
   public static MyClass Instance { get { return _myClass; } }

   public MyClass()
   {
      _myClass = this;
      ...
   }

   public void Hello()
   {
      Console.WriteLine("CIAO!")
   }
} 

And getting all the methods and properties of the class: 并获得该类的所有方法和属性:

MyClass.Instance.Hello();

You can pass also the class in a constructor, property or function, but i dislike this way... 你也可以在构造函数,属性或函数中传递类,但我不喜欢这种方式......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM