代码之家  ›  专栏  ›  技术社区  ›  Ayush

在其他类中引用Windows窗体元素

  •  4
  • Ayush  · 技术社区  · 15 年前

    我有一个windows窗体, Form1 ,带有文本框: tbx_Log

    在同一个项目的另一个类中,我想向日志文本框中写入一些内容,但不能在该类中引用tbx_log。我怎样才能做到这一点?

    5 回复  |  直到 15 年前
        1
  •  4
  •   jdehaan    15 年前

    访问其他类实例(对象)中的对象是错误的样式,并且违反了数据封装。将方法添加到 Form1 :

    public void SetLogText(String text)
    {
         tbx_Log.Text = text;
    }
    

        2
  •  2
  •   jafesler    15 年前

    您要么需要将文本框设置为公共(不推荐),要么向表单类添加一个将字符串写入文本框的公共方法(更好)。

    public class Form1
    {
        protected Textbox tbx_Log;
        public void Log(string str)
        {
            tbx_Log.Text += str + Environment.NewLine;
        }
    }
    
    public class Program
    {
        private void DoStuff()
        {
            Form1 myForm = new Form1();
            //Make form visible, etc...
            myForm.Log("Test Log");
        }
    }
    
        3
  •  2
  •   o. nate    15 年前

        4
  •  1
  •   Chris Taylor    15 年前

    与其直接引用tbx_日志,我建议您至少在表单中添加一个负责执行更新的方法。然后,您可以给您的类一个表单引用,并让您的类调用Forms日志函数,从而将文本添加到文本框中。

    我至少说过了,因为您可能希望定义一个接口,并让表单或稍后的更具体的日志类实现该接口,并让您的类与实现所定义接口的任何对象进行交互。

        5
  •  0
  •   Mikael Svenson    15 年前

    你可以在你的表格上公布方法。如果是从不同于UI线程的线程调用的话,也可以使其线程安全。

    public void SetText(string text)
    {
        // InvokeRequired required compares the thread ID of the
        // calling thread to the thread ID of the creating thread.
        // If these threads are different, it returns true.
        if (this.textBox1.InvokeRequired)
        {    
            SetTextCallback d = new SetTextCallback(SetText);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            this.tbx_Log.Text = text;
        }
    }
    

    有关winforms check上线程安全调用的完整示例和说明 MSDN ,这也说明了如何使用BackgroundWorker来实现线程安全性,这是首选的方法。