To navigate from one page to another, you can take advantage of the static Navigate method on the page’s read-only NavigationService property. This passes your request to the NavigationService Singleton for your application, and greatly simplifies the navigation syntax.
A Quick Demo
Demos should, in my opinion, be absolutely as simple as humanly possible, to keep the focus on the topic at hand. In that spirit, we’ll create a new application with just three pages:
- Main Page
- Page1
- Page2
For each page we’ll adjust the application title and page title, so that the page is self-identifying; e.g.,
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"> <TextBlock x:Name="ApplicationTitle" Text="Phone Nav" Style="{StaticResource PhoneTextNormalStyle}" /> <TextBlock x:Name="PageTitle" Text="Page 2" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}" /> </StackPanel>
On MainPage we’ll place two buttons, one saying Page 1 and the other saying Page 2. We’ll also implement event handlers for each, that use the Navigation service. Here is the complete code-behind for MainPage,
using System; using System.Windows; using Microsoft.Phone.Controls; namespace PhoneNav { public partial class MainPage : PhoneApplicationPage { public MainPage() { InitializeComponent(); Page1.Click += Page1_Click; Page2.Click += Page2_Click; } void Page2_Click( object sender, RoutedEventArgs e ) { NavigationService.Navigate( new Uri( "/Page2.xaml", UriKind.Relative ) ); } void Page1_Click( object sender, RoutedEventArgs e ) { NavigationService.Navigate( new Uri( "/Page1.xaml", UriKind.Relative ) ); } } }
Run the application. Clicking Page1 takes you there instantly (we may want to add animation at some point to make the transition less confusing).
For now, to navigate back, use the back button.
In the next mini-tutorial we’ll look at the events that are raised during navigation and how you can override them to take greater control of the navigation.
3 Responses to Windows Phone From Scratch – Navigation