How to access a control in one window form from other form

前端 未结 1 951
渐次进展
渐次进展 2021-01-27 19:13

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条回答
  • 2021-01-27 19:57

    You can do this in many ways...

    You can declare some static getter/setter to manage a static instance of the compononent:

    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

    MyClass.MyObject.Function();
    

    Or you can define a getter for the whole class:

    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...

    0 讨论(0)
提交回复
热议问题