I'm using two extensions to handle invoking commands on UI elements, adapted from this thread and others:
public static void InvokeIfRequired(this Control control, Action<Control> action)
{
if (control.InvokeRequired)
control.Invoke(new Action(() => action(control)));
else
action(control);
}
public static T InvokeIfRequired<T>(this Control control, Func<T> func) where T: IConvertible
{
if (control.InvokeRequired)
return (T)Convert.ChangeType(control.Invoke(func), typeof(T));
else
return (T)Convert.ChangeType(func, typeof(T));
}
These work just as expected
Button1.InvokeIfRequired(x => x.Enabled = false;
int newrow = DataGridView1.InvokeIfRequired(() => DataGridView1.Rows.Add());
when I need to call them from async methods.
However, I'm wondering if there's a way to further automate the InvokeIfRequired method -- is there a way to trigger the InvokeIfRequired when I set the property on the control without having to explicitly call InvokeIfRequired in the code?
Like, if I just type
Button1.Enabled = true;
is there a way to rangle the Set event or the control property so it calls InvokeIfRequired behind the scenes any time the .Enabled property is set? Or am I trying to put the cart before the horse and get too clever with this?