从应用程序的任何地方访问文本框 [英] access textbox from anywhere in application
问题描述
如何在我的 winforms 应用程序中创建一个文本框,以接受来自应用程序中任何位置的新文本行?
How can I make a textbox in my winforms application that accepts new lines of text from anywhere in the application?
我有一个包含文本框的主表单.我想从另一个类的方法中直接将文本添加到框中.
I have a main form that contains a textbox. I'd like to directly add text to the box from a method in another class.
更新
我以我的主要形式试过这个:
I tried this in my main form:
public void Output(String value)
{
if (txtOutput.Text.Length > 0)
{
txtOutput.AppendText(Environment.NewLine);
}
txtOutput.AppendText(value);
}
但是我不能从其他班级调用输出.我是 C# 新手,所以也许我遗漏了一些明显的东西.
But I can't call Output from the other class. I'm new to C#, so perhaps I'm missing something obvious.
问候,米尔.
PS 是的,我知道这是糟糕的设计,但就目前而言,这似乎是实现我想要的最佳方式.文本框的功能类似于控制台.
PS Yes, I know this is bad design, but for now this seems to be the best way to do what I want. The textbox would function like a console.
推荐答案
您需要将 TextBox
的 Text
属性公开为 string
表单上的属性.例如...
You'll need to expose the Text
property of the TextBox
as a string
property on your form. For example...
public string TextBoxText
{
get { return textBoxName.Text; }
set { textBoxName.Text = value; }
}
编辑
阅读问题编辑后,您的问题是,无论您在何处尝试执行该代码,都需要引用表单的特定实例.您可以传递一个引用(这是更好的选择),或者您可以使用一些臭代码并拥有一个静态属性来引用表单的一个实例.像……
After reading the question edit, your problem is that you need a reference to a specific instance of the form whereever you're trying to execute that code. You can either pass around a reference (which is the better option), or you could use some smelly code and have a static property that refers to one instance of your form. Something like...
public partial class MyForm : Form
{
private static MyForm instance;
public static MyForm Instance
{
get { return instance; }
}
public MyForm() : base()
{
InitializeComponent();
// ....
instance = this;
}
}
使用这种方法,您可以调用 MyForm.Instance.Output("test");
Using this approach, you could call MyForm.Instance.Output("test");
这篇关于从应用程序的任何地方访问文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!