Update textInput from outside its form
I have a form with a multiline textInput
. I need开发者_开发问答 to update the content of the textInput
from an object outside the form.
How can I achieve this? Should I use events, or perhaps pass the textInput
to the outside object's constructor?
Have a look at the MVP pattern - you could have your form implement an IView interface. Your other object would be the Presenter that would call, for example, IView.UpdateText() when something changes (or have your view subscribe to the presenters events - i prefer the method approach).
This separates your concerns and makes your solution more testable as you can mock up implementations of IView, IPresenter and IModel.
The form should check if this.InvokeRequired == true
to determine if the incoming request is on the UI thread. If it is not you will need to use a delegate.
public delegate void UpdateTextDelegate(string text);
public void UpdateText(string text)
{
// Check we are on the right thread.
if (!this.InvokeRequired)
{
// Update textbox here
}
else
{
UpdateTextDelegate updateText = new UpdateTextDelegate(this.UpdateText);
// Executes a delegate on the thread that owns the control's underlying window handle.
this.Invoke(updateText, new object[] { text });
}
}
i would not pass the text to the object. If you just need it as initialization value, passing the text to the constructor of the form would be fine. But not other way round.
Very simple solution: Give your form a public SetTextValue(string Text) method, that sets the text.
Events will work also, but seems a bit overpowered for such a simple problem.
There are a lot of ways to accomplish this depending on the specifics of what you're working on.
Update the text field from within the form?
txtField.Text = someObject.SomeProperty;
Set the value in the form's constructor?
SomeFormClass form1 = new SomeFormClass(aString);
form1.Show();
Call a method on the form from an external object?
public void SetText(string text) { txtField.Text = text; }
form1.SetText(aString);
Use data binding?
txtField.DataBindings.Add(new Binding("Text", someObject, "SomeProperty");
It's hard to answer without knowing more details.
精彩评论