In this post, we will learn about using navigation in Universal Windows Applications. As for a developer, they require navigation between pages in their application.
So, we will create an Universal Windows App in Visual studio and add another page in the solution explorer following steps below:
Go to Solution Explorer –> Right click on solution –> Add –> New Item –> Page –> Ok.
Now, after adding the new page, we will add a button to our MainPage.xaml to navigate from Main Page to the newly created page. Code for Xaml file :
1 2 3 4 5 | <Button Name="but" HorizontalAlignment="Center" VerticalAlignment="Center" Click="but_Click" Content="New page" /> |
Now, we will go to the .CS file of MainPage which is MainPage.xaml.cs and add the code for click event of the button added in the designer. The code for navigation to another page is as below:
1 2 3 4 | private void but_Click(object sender, RoutedEventArgs e) { this.Frame.Navigate(typeof(BlankPage1)); // BlankPage1 is the class of the page I added to the solution, put here the name of the class for the page you define while adding the page. } |
Now, we are done with the navigation from one page to another. But I want to navigate back from last page to the first page. For that I need to add Back button functionality to the solution so that we can navigate back and forth within the application.
To add Back button functionality, we will open App.xaml.cs file and add the following code in the OnLoaded event, inside if ( rootFrame == null ) block :
1 2 3 4 5 6 7 8 9 10 11 | rootFrame.Navigated += OnNavigated; // for back button // Code for Back button to be added // Register a handler for BackRequested events and set the // visibility of the Back button SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested; SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = rootFrame.CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed; |
We will add OnNavigated and event code in the App.xaml.cs file, which is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // code to be added for back button functionality private void OnNavigated(object sender, NavigationEventArgs e) { // Each time a navigation event occurs, update the Back button's visibility 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(); } } |
Now, our Universal Windows Application is ready for navigation functionality both back and forth. Run the application and enjoy!