0

I'm using WindowsTemplateStudio, In ShellPage.xaml.cs, I want to detect if the user changed network, app navigate to a specified page.

So I used

Microsoft.Toolkit.Uwp.Connectivity.NetworkHelper.Instance.NetworkChanged += Instance_NetworkChanged;
private async void Instance_NetworkChanged(object sender, EventArgs e)
{
   //NavigationService.Navigate(page);
   shellFrame.Navigate(typeof(page));
}

But this caused System.Exception. How to handle this, and navigate to a page, thx.

Vincent
  • 3,124
  • 3
  • 21
  • 40

1 Answers1

1

Navigate to page in ShellPage.xaml.cs caused exception

The problem is NetworkChanged invoked in un-uithread, but Navigate method need uithread environment. So please call Dispatcher in NetworkChanged event handler.

private async void Instance_NetworkChanged(object sender, EventArgs e)
{
 await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
  {
    shellFrame.Navigate(typeof(page));
  });
}
Nico Zhu
  • 32,367
  • 2
  • 15
  • 36