backendev
backendev

Reputation: 267

Automatic navigation to next page fails in Windows Store App

I have a page X in a Windows Store App (Windows 8.1) that gets shown after the splash screen. I want to evaluate something while / after the page loads, before the user can interact with the page.

Depending on the evaluation I want to do one of the two:

  1. Just show the page X to the user and only navigate to page Y when the user clicks a button
  2. Skip the current page and navigate to page Y automatically

1 works fine.

2 doesn't. I tried with calling this.Frame.Navigate(typeof(Y)) in the constructor, which didn't work because this.Frame was still null. Then I tried calling it in LoadState and OnNavigatedTo, but while in both cases this.Frame is not null, the Navigate() method returns false, which means the navigation fails. I tried to step into the method in Debugging, but it didn't work (?).

One hint is, that when hitting a breakpoint in the Navigate() code line when it gets called automatically, the screen still shows the splash screen, so it seems the UI elements have not been loaded yet. So the final question is: How can I do the evaulation and automatic navigation with all elements being loaded (or just so that it works)?

Upvotes: 1

Views: 982

Answers (1)

andreask
andreask

Reputation: 4298

I don't see why you would call Frame.Navigate(...) in OnNavigatedFrom, but I can suggest two options that work for me:

  1. Navigate to the second page in OnNavigatedTo: Although this doesn't work out of the box, it does when instructing the dispatcher to do the navigation:

    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }
    
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
    
            this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                this.Frame.Navigate(typeof(SecondPage));
            });
        }
    }
    
  2. An even easier solution is to do the navigation within the first page's Loaded event:

    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
    
            this.Loaded += (sender, args) =>
            {
                this.Frame.Navigate(typeof(SecondPage));
            };
        }
    }
    

Of course, in both cases you can add whatever calculation you like within the lambda expression before calling Frame.Navigate(...)

EDIT: As a third alternative, maybe you should think about moving the calculation and decision part to OnLaunched in App.xaml.cs, and load either the first or the second page as root page, instead of opening the first page and immediately navigating on to the second?

Upvotes: 4

Related Questions