Gotcha–navigating from SplitView requires back button to be pressed twice in UWP apps
All went rosey, until I discovered that altough the back button showed up nicely on my secondary page, the actual navigation back only happenend after I had pressed the back button twice. Some debugging learned me the global event
SystemNavigationManager.GetForCurrentView().BackRequesteddoes not even get called the first time. I spent a not so enjoyable hour deconstructing my app, then finally building a bare bones repro – and there it happened too. One of those moment where you seriously start to doubt your own mental health. The code is not very complicated. I have a MainPage.xaml with a button on a SplitView, and when you click that, it navigates to the next page
private void Navigation_Click(object sender, RoutedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; rootFrame.Navigate(typeof(Page2)); }And on that Page2 a rather piece of standard code
protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); var rootFrame = Window.Current.Content as Frame; if (rootFrame != null) { SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = rootFrame.CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed; } }And in the app.xaml.cs, also rather standard (and ugly, now that I look at it), nicked from the sample
private void App_BackRequested(object sender, BackRequestedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; if (rootFrame == null) return; if (rootFrame.CanGoBack && e.Handled == false) { e.Handled = true; rootFrame.GoBack(); } }And yet, this method gets only called on the second back button press. The solution? Read back a little.
“I have a MainPage.xaml with a button on a SplitView, and when you click that, it navigates to the next page”
It's one of those mental leaps you sometimes have to make as a developer. It turns out that the exact method Navigation_Click works flawlessly when the button calling the method is not on a SplitView. Somehow, some way, having a SplitView open messes up the navigation back stack.
The solution, once you know that, is very simple of course:
private void Navigation_Click(object sender, RoutedEventArgs e) { rootSplitView.IsPaneOpen = false; Frame rootFrame = Window.Current.Content as Frame; rootFrame.Navigate(typeof(Page2)); }Go back to the click event handler, and add a line that closes the SplitView before initiating the navigation. It’s the little things like this that makes developer life so interesting. ;)
Code used in this post can be found here.
Special thanks to Scott Lovegrove and the other people from the Open Live Writer team for making this post possible – it’s the first one using Open Live Writer that now supports blogger – right after Google shut down the outdated web api endpoint that Live Writer still used. Thank you all folks!