将信息从类发送到表单的文本框

时间:2012-11-08 20:05:48

标签: c# winforms forms instances

我几天前问过一个关于在类中填充表单上的列表框的问题。它的工作原理很棒!但是我现在想用文本框或标签做同样的事情。该问题的答案如下:

  

您正在做的是创建表单的新实例 - 我猜想   您是否尝试在现有表单的列表框中添加项目?

     

如果是这样的话。

     

使用列表框在表单上创建一个函数,如:

    public void addItemToListBox(string item)
    {
         listBox1.Items.Add(item);
    }
     

然后,在类中(记得添加使用System.Windows.Forms   参考)

   public void doStuff()
    {
 //Change Form1 to whatever your form is called
 foreach (Form frm in Application.OpenForms)
 {
      if (frm.GetType() == typeof(Form1))
      {
           Form1 frmTemp = (Form1)frm;
           frmTemp.addItemToListBox("blah");

      }
 }
    }

这很有效。现在我想用文本框做同样的事情。我想知道是否有人可以解释或是否有人有这方面的链接?

我有一个表格和一个班级。该表单创建了一个类的新实例,并在类中启动一个方法,比如数学等式4 + 4;我想要答案,“8”然后在class1的文本框或标签中显示,来自类中的方法。

4 个答案:

答案 0 :(得分:2)

通过编辑,您所描述的内容是Form 使用另一个类的模型。正在使用的类应该不了解Form,它的控件,或者如何使用它的计算结果。

您的其他课程不应该找到该表格,不应该调用表格的任何方法或字段,或任何内容。它应该做的只是返回一个值:

public class OtherClass
{
    public int Add(int first, int second)
    {
        return first + second;
    }
}

然后表单可以执行以下操作:

private void button1_Click(object sender, EventArgs e)
{
    //create an instance of the other class
    OtherClass other = new OtherClass();
    //call it's add method, and then use the result to set the textbox's text
    textbox1.Text = other.Add(4, 4).ToString(); 
}

另一个类应负责进行计算,创建结果,但不根据这些结果更新用户界面。所有用户界面逻辑都应包含在Form类中。

答案 1 :(得分:1)

将它放在Form1.cs中:

public void SetText(string text)
{
    textBox1.Text = text;
}

在课程文件中:

frmTemp.SetText("XYZ");

答案 2 :(得分:1)

通过所有开放形式循环似乎是......新颖的...获得有问题的形式的方式。

相反,你应该保留对表单的引用,直到你最终关闭它,并直接通过它访问表单上的变量(如列表框和文本框)。

因此,在创建表单的地方,执行类似

的操作
Form1 form1 = new Form1();

//打开对话框或使用form1进行的任何操作

//当您需要访问文本控件时:

form1.textBox1.Text = "Some value"; // Assumes the control is called textBox1

如果 doStuff 是从一个模型(一个模拟现实世界行为某些方面的类)发生的,那么你就是在遵循一个糟糕的设计模式。

模型应该不知道它们是如何呈现的。相反,在典型的WinForms应用程序中,父表单可能会保存变量 form1 。在较新类型的UI项目中,您将看到MVC或MVVM模式来分离模型,视图(表示/表单)和控制器(流控制)。也可以使用WinForms遵循MVC模式,尽管我见过的许多/大多数WinForms应用程序都没有这样做。

答案 3 :(得分:0)

如果您使用的是Visual Studio,则可以指定每个成员的可见性,例如: privatepublicprivate是默认值(如果我没记错的话)。

如果将其更改为public,则可以执行以下操作:

public void doStuff()
{
 //Change Form1 to whatever your form is called
 foreach (Form frm in Application.OpenForms)
 {
  if (frm is Form1)
  {
       var frmTemp = (Form1)frm;
       frmTemp.listBox1.Items.Add("blah");
       frmTemp.textBox1.Text += "hello world";
  }
 }
}

编辑1
更好的方法是告诉Form1它需要更新某些东西,它如何呈现数据与调用该方法的类无关。

private Form1 _FindForm()
{
   //assuming you can use Linq
   return Application.OpenForms.OfType<Form1>().Single();
}

public void displaySomething()
{
   var form = _FindForm();
   form.displaySomething();
}

public class Form1
{
  public void displaySomething()
  {
    //add an item to the list box
    listBox1.Items.Add("foo");

    //and change the text somewhere
    textBox1.Text += "bar";
  }
}

Form1现在负责更改它所持有的控件,而不是其他 - 可能 - 不相关的类操作它们。 这将所有UI逻辑encapsulated保存到Form1中,并且所有业务逻辑都可以保存在其他位置。