While I was migrating my App to
Windows 10 UWP, I faced some issues implementing back navigation and related things. I've found a few solutions with different implementation. I'm combining all those things here with the proper code. So, this will be a complete solution to implement back navigation and related concepts in your UWP App.
This article is geared for app development in UWP Windows 10 with C# and XAML.
While coding a UWP app, you need to take care of two platforms; mainly, Windows Phone and other Windows devices (including tablet and desktop/surface hub). While in some devices you'll get a hardwared back button for backward navigation so you don't need to include UI for the back button in your app, whereas in the desktop you need to include a Back Button in your application's UI.
There are two ways to manage backward navigation in UWP
- Implement Windows.UI.Core.SystemNavigationManager API
- Implement custom logic with Back Button in Application's UI
Let's elaborate this in detail with code examples.
Implementing SystemNavigationMnager
There are two benefits of using SystemNavigationManager.
- If the App is running on the device which doesn't have hardware back button, it'll show the back button onthe application's window header.
- You don't need to import any external SDK to do this.
To make that back button visible on the specific page and handle the click event of that back button, write the following code in the page's constructor or in Loaded event of that page.
- SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
- SystemNavigationManager.GetForCurrentView().BackRequested += (s, e) =>
- {
-
- };
The real essence of using this technique is to implement SystemNavigationManager in a way so that you don't need to write this code in every page but you can manage it throughout the App.
To do that, you need to make some changes in App.xaml.cs file of your App.
You need to add some code to your OnLaunched event handler as below. The code to be added is highlighted in red ink.
- protected override void OnLaunched(LaunchActivatedEventArgs e)
- {
-
- Frame rootFrame = Window.Current.Content as Frame;
-
-
-
- if (rootFrame == null)
- {
-
- rootFrame = new Frame();
-
- rootFrame.NavigationFailed += OnNavigationFailed;
- rootFrame.Navigated += RootFrame_Navigated;
-
- if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
- {
-
- }
-
-
- Window.Current.Content = rootFrame;
-
-
-
- SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
-
- SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
- rootFrame.CanGoBack ?
- AppViewBackButtonVisibility.Visible :
- AppViewBackButtonVisibility.Collapsed;
-
- }
-
- if (rootFrame.Content == null)
- {
-
-
-
- rootFrame.Navigate(typeof(Page1), e.Arguments);
- }
-
- Window.Current.Activate();
- }
Now, add two event handlers in App.xaml.cs file as below which we've declared in above code.
- private void RootFrame_Navigated(object sender, NavigationEventArgs e)
- {
-
- SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
- ((Frame)sender).CanGoBack ?
- AppViewBackButtonVisibility.Visible :
- AppViewBackButtonVisibility.Collapsed;
- }
-
- private void OnBackRequested(object sender, BackRequestedEventArgs e)
- {
- Frame rootFrame = Window.Current.Content as Frame;
-
- if (rootFrame.CanGoBack)
- {
- e.Handled = true;
- rootFrame.GoBack();
- }
- }
That's it.
By adding above code in App.xaml.cs you'll get a fully functional Back Button throughout your App.
Note: You can find more detail about the above solution from the following
blog.
Implement your own logic with Back Button in the App UI
While implementing custom logic, the important thing to take care is of showing the back button on Windows Desktopm but hiding it while in the Windows phone. For that we need to detect which device the app is running on. To detect that we have two options.
- Use VisualStateManager in XAML
- Detecting through backend code
Sometimes using VisualStateManager to detect whether the app is running on the Windows phone or desktop can cause inaccuracy because the user can resize the App window in Desktop mode. Though the code should look like this:
- <VisualStateManager.VisualStateGroups>
- <VisualStateGroup>
- <VisualState x:Name="visualStateDesktop">
- <VisualState.StateTriggers>
- <AdaptiveTrigger MinWindowWidth="700" />
- </VisualState.StateTriggers>
- <VisualState.Setters>
- <Setter Target="btnBack.Visibility" Value="Visible" />
- </VisualState.Setters>
- </VisualState>
-
- <VisualState x:Name="visualStateMobile">
- <VisualState.StateTriggers>
- <AdaptiveTrigger MinWindowWidth="0" />
- </VisualState.StateTriggers>
- <VisualState.Setters>
- <Setter Target="btnBack.Visibility" Value="Collapsed" />
- </VisualState.Setters>
- </VisualState>
- </VisualStateGroup>
- </VisualStateManager.VisualStateGroups>
Here btnBack is the name of back button which we've added as in the following screenshot:
Now, to detect the platform (whether Windows phone or desktop) by C# code we just need to add one method in App.xaml.cs page.
- public static Platform DetectPlatform()
- {
- bool isHardwareButtonsAPIPresent = ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons");
-
- if (isHardwareButtonsAPIPresent)
- {
- return Platform.WindowsPhone;
- }
- else
- {
- return Platform.Windows;
- }
- }
This method will return enum value of Windows.Foundation.Metadata.Platform. We can use this method something like this.
- if (App.DetectPlatform() == Platform.WindowsPhone)
- {
- HardwareButtons.BackPressed += new EventHandler<BackPressedEventArgs>((s, a) =>
- {
- if (frameContent.CanGoBack)
- {
- frameContent.GoBack();
- a.Handled = true;
- }
- });
- }
Using this method is important here because Windows.Phone.UI.Input.HardwareButtons class will only available through Windows Mobile Extension for the UWP in reference manager.
So while runningthe app on the Windows desktop an exception will fire while executing HardwareButtons.BackPressed line of code if there will not be any condition to check the current platform.
Conclusion
So in this article we've covered the following topics:
- Back navigation
- Using Default API for Back Navigation (SystemNavigationmanager)
- Managing Back Button visibility on Windows desktop through VisualStateManager
- Handling hardware BackButton in Windows phone
- Detecting platform whether Windows Phone or Windows
I hope this article will be helpful. If you find anything to include or change, please comment.
Read more articles on Universal Windows Apps: