0

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?

John
  • 11
  • 4
  • If you need it that much, your overall design is in trouble. Separate your business logic from your presenation logic better. – H H Sep 06 '18 at 21:46
  • @HenkHolterman It's not so much a need as kind of a way to further my programming knowledge. It works perfectly fine as-is, but I'm always looking for more options. – John Sep 06 '18 at 22:13

0 Answers0