C#.NET更改文本框的文本

时间:2023-01-06 19:14:10

How do we call a form1 class event from another class present in form1.cs?

我们如何从form1.cs中的另一个类调用form1类事件?

public partial class form1 : form
{
// an event to change the text of a textbox
}

public class A
{
sendtext()
{
//text to be sent to the texbox
// the text is created as a output of a thread
}

2 个解决方案

#1


2  

You should create an event in A class and subscribe to it from form1.

您应该在A类中创建一个事件并从form1订阅它。

class A
{
   public event Action<string> TextReady;

   private OnTextReady(string text)
   {
      var ev = TextReady;
      if(ev!=null) ev(text);        
   }
}

class Form1
{
   private _a = new A();
   public Form1()
   {
      _a.TextReady+= (text)=> textBox.Text = text;
   }
}

You will probably stumble into cross-thread limitations, but that's another question, just write a comment if you will.

您可能会遇到跨线程限制,但这是另一个问题,如果您愿意,只需撰写评论即可。

#2


1  

You can always just change the text directly.

您可以随时直接更改文本。

public partial class form1 : form
{
    public string TextboxText 
    {
        get { return txtBox.Text; }
        set { txtBox.Text = value; }
    }
}

Then just do:

然后就做:

form1.TextboxText = "My new text";

#1


2  

You should create an event in A class and subscribe to it from form1.

您应该在A类中创建一个事件并从form1订阅它。

class A
{
   public event Action<string> TextReady;

   private OnTextReady(string text)
   {
      var ev = TextReady;
      if(ev!=null) ev(text);        
   }
}

class Form1
{
   private _a = new A();
   public Form1()
   {
      _a.TextReady+= (text)=> textBox.Text = text;
   }
}

You will probably stumble into cross-thread limitations, but that's another question, just write a comment if you will.

您可能会遇到跨线程限制,但这是另一个问题,如果您愿意,只需撰写评论即可。

#2


1  

You can always just change the text directly.

您可以随时直接更改文本。

public partial class form1 : form
{
    public string TextboxText 
    {
        get { return txtBox.Text; }
        set { txtBox.Text = value; }
    }
}

Then just do:

然后就做:

form1.TextboxText = "My new text";