Frame navigation in xaml return false

2019-02-14 06:06发布

问题:

Hello,
I'm working in a simple Windows 8 application with xaml and c#. I'm using the VS 2012 templates to create pages, with navigation system included.

I'm loading a lot of data, so I decided to add a loading page with a ProgressRing and navigate to the first Application page when loading data is finished:

//loading page
protected async override void OnNavigatedTo(NavigationEventArgs e) {
...
await topCookerManager.GetBlogsAsync();
this.Frame.Navigate(typeof(MainPage));
...
}

It works well when application is starting, but when I'm on the first page of application and when I'm click on back button I'm redirect to the loading page. So, in the loading page I'm checking if data are loaded and if yes I redirect to the first page.

if (dataManager.Blogs != null && dataManager.Blogs.Count > 0)
this.Frame.Navigate(typeof(MainPage));

**That's the problem**: I' can't navigate from this point. The Navigate method return false ! I've tested *GoFormard* method, it throw no exception but navigation is not done and I'm staying on the loading page...

Could you please tell me where is my mistake ? Or how implement a loading page.
Thanks for your help.

回答1:

You can't Navigate from within the OnNavigatedTo method as the previous navigation method is still executing at that point. Instead, you can wait for it to be loaded by running the new navigation call via a dispatcher.

protected async override void OnNavigatedTo(NavigationEventArgs e)
{
     //your other code
     //...
     Dispatcher.RunAsync(CoreDispatcherPriority.Normal, 
                            () => Frame.Navigate(typeof(MainPage))); 
}

The reason why it may work the first time in your code is because you're waiting for a few moments for the blogs to load. Within this time, the navigation method has completed loading and so it can be called again.

Having said that, consider if you really wanting a loading page and not just an overlay of some sort as Xyroid mentioned in the comments.