Search code examples
c#wpfreferencedispatcherref

C# - Component reference - Dispacher.CheckAccess()


I have a problem. I need to use the function which passes one argument (a reference to a control):

public void recalculateFontSize(ref TextBlock component)
{
...
}

I want to use it but don't know how to connect Dispatcher with "ref" keyword:S

    private void textResizer(ref TextBlock component)
    {
        if (component.Dispatcher.CheckAccess())
        {
            textUtils.recalculateFontSize(ref component);
        }
        else
        {
            component.Dispatcher.Invoke(new Action<TextBlock>(textResizer), component);
        }
    }

How to modify component.Dispatcher.Invoke ???


Solution

  • Passing UI controls around is always almost bad idea i would say.

    Why not tweak the logic a bit so that you can using Binding in your View (i take it you are using WPF as Dispatcher is involved)

    so that your ViewModel will expose RecalculateFontSize command and then your View is bound to a Font Size property that ViewModel can change on per request basis.

    That way in your Command you can check for access via Dispatcher.CheckAccess and invoke the recalculation of the FontSize in the UI thread.