[英]access textbox from anywhere in application
如何在Winforms應用程序中制作一個文本框,以接受應用程序中任何位置的新文本行?
我有一個包含文本框的主窗體。 我想直接從另一個類的方法將文本添加到框中。
更新
我嘗試了我的主要形式:
public void Output(String value)
{
if (txtOutput.Text.Length > 0)
{
txtOutput.AppendText(Environment.NewLine);
}
txtOutput.AppendText(value);
}
但是我不能從另一個類調用Output。 我是C#的新手,所以也許我缺少明顯的東西。
問候,米爾。
附言:是的,我知道這是不好的設計,但就目前而言,這似乎是實現我想要的最佳方法。 該文本框的功能類似於控制台。
您需要在窗體上將TextBox
的Text
屬性公開為string
屬性。 例如...
public string TextBoxText
{
get { return textBoxName.Text; }
set { textBoxName.Text = value; }
}
編輯
閱讀問題編輯后,您的問題是,無論您要執行該代碼的何處,都需要引用該表單的特定實例。 您可以傳遞一個引用(這是更好的選擇),也可以使用一些臭代碼並具有引用表單的一個實例的靜態屬性。 就像是...
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");
為了進一步解耦,您可以將控件反一點:
// interface for exposing append method
public interface IAppend
{
void AppendText(string text);
}
// some class that can use the IAppend interface
public class SomeOtherClass
{
private IAppend _appendTarget = null;
public SomeOtherClass(IAppend appendTarget)
{
_appendTarget = appendTarget;
}
private void AppendText(string text)
{
if (_appendTarget != null)
{
_appendTarget.AppendText(text);
}
}
public void MethodThatWillWantToAppendText()
{
// do some stuff
this.AppendText("I will add this.");
}
}
// implementation of IAppend in the form
void IAppend.AppendText(string text)
{
textBox1.AppendText(text);
}
您的設計似乎已損壞。 您不應該讓商務邏輯與GUI控件混淆。 為什么不嘗試返回值並在接口側分配它呢?
這確實是一個很糟糕的方法,但是只是要確保所有答案都在那里。
在VS設計器中,每個窗體控件在“屬性”窗口中都有一個名為“ Modifiers
,默認為“ Private
。 將其更改為其他設置之一,例如Internal
或Public
,將使您可以從表單外部訪問它。
我必須強調,這是最糟糕的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.