Navigating between pages
It is quite difficult to imagine an application with only one page. Thus, it is crucial to know how to navigate from one page to another. In this recipe, you will learn how to navigate to another page after pressing the button as well as how to go back to the previous page after pressing the button on the other page.
Getting ready
To complete this recipe, you need the project with two pages, represented by the MainPage
and AboutPage
classes. Let's imagine that the first page operates as a main menu of the application with a set of buttons. After clicking on each of them, a user should be navigated to a particular page, such as with information about the company, with a list of products, or with contact data.
As an example, the Button
control should be added to both the pages, namely MainPage
and AboutPage
. However, they should present different content, such as About us (in MainPage
) and Go back (in AboutPage
), as graphically explained as follows:
How to do it...
To prepare an example that shows how to navigate between pages, you need to perform the following steps:
To navigate from
MainPage
toAboutPage
, modify the code of thebutton_Click
method in theMainPage.xaml.cs
file, as follows:private void button_Click(object sender, RoutedEventArgs e) { Frame.Navigate(typeof(AboutPage)); }
To go back to the previous page from
AboutPage
, modify the code of thebutton_Click
method in theAboutPage.xaml.cs
file, as follows:private void button_Click(object sender, RoutedEventArgs e) { if (Frame.CanGoBack) { Frame.GoBack(); } }
How it works...
Navigation to another page is possible using the Frame
property of the Frame
type. It provides developers with a few methods, including Navigate
and GoBack
.
The first method (Navigate
) is used to navigate the user to another page with or without additional parameters (take a look at the next recipe), while the other (GoBack
) allows the user to go back to the previous page. In such a case, it is recommended that you check whether you can go back to the previous page by verifying whether the CanGoBack
property has a value equal to true
.
See also
The Passing data between pages recipe
The Handling the back button recipe
The Changing a default page recipe
The Modifying the back stack recipe