简体   繁体   English

如何从C#中的其他表单访问可视组件

[英]How to access a visual component from another form in c#

I have a textbox in my main form. 我的主窗体中有一个文本框。

Now I have created a function which is used to set the value of the text box. 现在,我创建了一个函数,用于设置文本框的值。

public void SetTextOfTextBox(String text)
{
  textbox1.text = text;
}

Now in my main form I call another class (class b) which does some work for me. 现在,以我的主要形式,我叫另一个类(b类),它为我做了一些工作。 Now i want to be able to call my setTextofTextBox function from class b. 现在,我希望能够从类b调用我的setTextofTextBox函数。

Now if I try Form1.SetTextOfTextBox("test"); 现在,如果我尝试Form1.SetTextOfTextBox("test"); this doesn't work. 这行不通。 What am I doing wrong? 我究竟做错了什么?

How do I access components of aa Form from another class. 如何从另一个类访问aa Form的组件。

Form1.SetTextOfTextBox("test"); Form1.SetTextOfTextBox(“ test”); this doesn't work 这不起作用

This doesn't work because SetTextOfTextBox is not static and you cannot access a non-static function directly. 这不起作用,因为SetTextOfTextBox不是静态的,并且您不能直接访问非静态的函数。 And you can't make it static either because your textbox is form level control. 而且您也不能使其静态,因为您的文本框是表单级控件。

How do I access components of aa Form from another class 如何从另一个类访问aa Form的组件

You will have to pass the instance of Form1 to your other class to access it. 您必须将Form1的实例传递给其他类才能访问它。 Something like 就像是

  Class B = new ClassB(this);  //where this is the instance of Form1.

You will need a reference to the instance of Form1 in class b, otherwise you cannot call member methods. 您将需要对类b中的Form1实例的引用,否则您将无法调用成员方法。

Something like this: 像这样:

class Form1 : System.Windows.Forms.Form {
    void functionInForm1() {
        ClassB objB = new ClassB();
        objB.doSomething(this);
    }
}

class ClassB {
    void doSomething(Form1 form) {
        form.SetTextOfTextBox("test");
    }   
}

Find out the Form1 and call the method: 找出 Form1并调用方法:

  foreach (var form in Application.OpenForms) {
    Form1 myForm = form as Form1;

    if (!Object.ReferenceEquals(null, myForm)) {
      myForm.SetTextOfTextBox("Test");

      break;
    }
  }

Did u try using delegates. 您是否尝试使用委托。

Specify the delegates in your ClassB like this. 像这样在ClassB中指定委托。

public delegate void OnDone(string textValue);
public event OnDone OnUserDone;

after completing the task in ClassB call event: 在ClassB通话事件中完成任务后:

OnUserDone("DoneClassB");

When u create the object of class in form map delegate function. 当您在表单映射委托函数中创建类的对象时。

 Classb b=new Classb();
 b.OnUserDone += new Classb.OnUsrControlDone(CompletedClasss);

Define the function in form like below. 以如下形式定义函数。

void CompletedClasss(string textValue)
{
            SetTextOfTextBox( textValue);
}

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

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