Reputation: 841
I have the following code inside a public
method, however how would I use it in a static method? o
is a static TextBox
?
Invoke((MethodInvoker)delegate {
o.Text = str + Environment.NewLine;
});
I have read up on the MethodInfo class in the System.Reflection
namespace, but nothing seems to be working. Just to show you, I want something that does this:
public static void writeOut(string str)
{
Invoke((MethodInvoker)delegate {
o.Text = str + Environment.NewLine; // runs on UI thread
});
}
That code does not work, but I want to know how to do something that can call in invoke
in a static method, like the snippet above.
Upvotes: 1
Views: 4605
Reputation: 70701
The direct answer to your question is to use the o.Invoke()
method:
public static void writeOut(string str)
{
o.Invoke((MethodInvoker)delegate {
o.Text = str + Environment.NewLine; // runs on UI thread
});
}
I.e. assuming that o
is a valid identifier in this context, and assuming it does in fact refer to a TextBox
object, then you can just call that TextBox
object's Invoke()
method.
That said, I agree with the comments that point out that having a static
reference to a control instance in your form is a really bad idea. It's a hack that means you can only ever have one instance of your form, and it means it relies on correctly initializing the static
field in an instance method (e.g. the constructor).
If you must have a static
reference at all, make it to the form object itself. Even better, pass the form object reference to whatever object needs to deal with it. There's not enough context in your question for me to suggest what exactly that would look like, but the basic idea is to only make things static
for things that are truly static, i.e. not related at all to a type that could be instantiated more than once.
As far as the suggestions to learn WPF go…
WPF is definitely a step up and worth learning but it's a much steeper curve than is Winforms. Winforms has a straightforward control object and event-driven model, with some minimal data binding features thrown in. WPF relies heavily on strong "separation of concerns" programming methodologies, data binding, and the use of an entirely different language to define the UI itself (i.e. XAML). These methodologies are very useful and when implemented correctly will lead to much better, more maintainable code. But it's a lot more work to learn to use them, and the WPF API itself is very complicated, and in many areas without a clear single choice for how to implement something.
Upvotes: 1