0

I'm creating a library. One thing that we need is the screen resolution of the phone in pixels(width by height)

We were using this method successfully

Screen.Width = (int) System.Windows.Application.Current.Host.Content.ActualWidth;
Screen.Height = (int) System.Windows.Application.Current.Host.Content.ActualHeight;

but then we don't handle the case where this method is called by a background thread, so we changed it to use Dispatcher:

System.Windows.Application.Current.RootVisual.Dispatcher.BeginInvoke(() =>
  {
    Screen.Width = (int) System.Windows.Application.Current.Host.Content.ActualWidth;
    Screen.Height = (int) System.Windows.Application.Current.Host.Content.ActualHeight;
  });

However, we an "invalid cross thread access" exception thrown, seemingly at just making use of BeginInvoke.

How can we properly handle this without having a reference to the currently rendered XAML page?

Earlz
  • 62,085
  • 98
  • 303
  • 499

1 Answers1

2

Just accessing Application.Current.RootVisual throws an invalid cross thread access exception, so you can't access the dispatcher this way. Instead, use System.Windows.Deployment.Current.Dispatcher:

System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
    Screen.Width = (int) System.Windows.Application.Current.Host.Content.ActualWidth;
    Screen.Height = (int) System.Windows.Application.Current.Host.Content.ActualHeight;
});
Kevin Gosse
  • 38,392
  • 3
  • 78
  • 94