App Hub

Visuals & Media

Make your applications visually appealing with images, animations, and media.

Sensors & Other Phone Specific Features

Use unique features of the phone, such the accelerometer, GPS, and camera, in your applications.

Navigation
Silverlight quickstart for Windows Phone development

Navigation in Windows Phone can be defined as enabling users to move through the different pages of content. The navigation model in Windows Phone enables you to create view-based applications that match the look and feel of Windows Phone. This QuickStart shows you how to navigate between different pages in your application.

This QuickStart contains the following sections:

Frames and Pages

The navigation experience in Windows Phone is similar to the navigation experience in Silverlight, but it has been extended to accommodate phone-specific features. The navigation model in Windows Phone is based on one PhoneApplicationFrame control. PhoneApplicationFrame contains one or more PhoneApplicationPage controls that users can navigate through. PhoneApplicationFrame is the main navigation control and supports navigation to and from pages. PhoneApplicationPage encapsulates content that can be navigated to by PhoneApplicationFrame.

Frame and Pages

A page is a collection of persistent state. It can be viewed as a Silverlight page that contains content or links to other pages. An application can also contain pop-ups, message boxes, a login screen, or a splash screen that typically doesn't contain a persistent state.

Only moving between two pages is considered navigation in Windows Phone. Moving from a login screen or a splash screen to the Home page isn't considered to be navigation and can be referred to as a transition.

Navigating between Pages

The easiest way to perform page navigation is by using a HyperlinkButton control. You can use its NavigationUri property to navigate to a page. The following example shows how to navigate to a page named SecondPage.xaml.

XAML

<HyperlinkButton NavigateUri="SecondPage.xaml" />

If you don't want to use a HyperlinkButton, you can perform navigation by using the NavigationService class. This class contains several properties, methods, and events to help you with navigation. You can use the NavigationService.Navigate method to navigate to a specific page. To navigate from one page to another page, perform the following steps.

  1. Create a Windows Phone application in Visual Studio.
  2. Add a Windows Phone Portrait Page named SecondPage.xaml that you can navigate to from MainPage.
  3. Use the NavigationService.Navigate method to navigate to SecondPage.xaml.
  4. Use the NavigationService.GoBack method to go back to MainPage.xaml.

The following example creates two pages called home page and second page. You can navigate from the home page to the second page by clicking the Go to the second page button in the home page. This is achieved by using the NavigationService.Navigate method with the URI for the second page (which is /SecondPage.xaml) in the button's Click event handler. You can return to the second page by clicking the "Go Back to Main Page" button in the second page. This is achieved by calling the NavigationService.GoBack method in the button's Click event handler. The NavigationService.GoBack method navigates to the most recent entry in the back navigation history, in this case the home page. Before calling the NavigationService.GoBack method, you should check the value of NavigationService.CanGoBack property to determine if an entry exists in the back navigation history.

Tip

Although the NavigationService.GoBack method was used in this example to go back to the home page, clicking the hardware Back button would also navigate to the previous page.

XAML for MainPage.xaml

<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0"
Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="Navigation"
Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="home page"
Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button x:Name="MyButton" Height="100" Width="350"
Click="MyButton_Click" Content="Go to Second Page"/>
</Grid>
</Grid>

C# for MainPage.xaml.cs

private void MyButton_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/SecondPage.xaml",
UriKind.RelativeOrAbsolute));
}

Visual Basic for MainPage.xaml.cs

Private Sub MyButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
NavigationService.Navigate(New Uri("/SecondPage.xaml", UriKind.RelativeOrAbsolute))
End Sub

XAML for SecondPage.xaml

<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0"
Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="Navigation"
Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="second page"
Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button x:Name="BtnBack" Content="Go Back to Home Page"
Click="BtnBack_Click" Height="100" Width="350"/>
</Grid>
</Grid>

C# for SecondPage.xaml.cs

private void BtnBack_Click(object sender, RoutedEventArgs e)
{
if (NavigationService.CanGoBack)
NavigationService.GoBack();
}

Visual Basic for SecondPage.xaml.cs

Private Sub BtnBack_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
If NavigationService.CanGoBack Then
NavigationService.GoBack
End If
End Sub

The following illustration displays the home page and the second page for the previous example. Navigation is achieved by using the NavigationService.Navigate and NavigationService.GoBack methods.

Home and second pages

Passing Data Between Pages

Often, you'll want to pass data from one page to another while navigating between pages. For example, you might want to pass the text that is typed by the user in the home page and display it in the second page. You can call the NavigationService.Navigate method to navigate to the second page and pass the string data entered in the home page to the second page in the URI as a query string. You can then override the Page.OnNavigatedTo method in the SecondPage.xaml.cs to examine the navigation request from the home page and extract the string data. The following example shows how you can pass data from one page to another by using the NavigationService.Navigate and Page.OnNavigatedTo methods.

XAML for MainPage.xaml

<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0"
Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="Navigation"
Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="home page"
Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<StackPanel x:Name="ContentPanel" Grid.Row="1"
Margin="12,0,12,0">
<TextBox x:Name="MyTB" Height="80"
Width="350" />
<Button x:Name="MyButton" Content="Go to Second Page"
Height="80" Width="350" Click="MyButton_Click"/>
</StackPanel>
</Grid>

C# for MainPage.xaml.cs

private void MyButton_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/SecondPage.xaml?msg=" +
MyTB.Text, UriKind.RelativeOrAbsolute));
}

Visual Basic for MainPage.xaml.cs

Private Sub MyButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
NavigationService.Navigate(New Uri(("/SecondPage.xaml?msg=" + MyTB.Text), UriKind.RelativeOrAbsolute))
End Sub

XAML for SecondPage.xaml

<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0"
Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="Navigation"
Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="second page"
Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBlock x:Name="MyTBl" FontSize="25"/>
</Grid>
</Grid>

C# for SecondPage.xaml.cs

protected override void OnNavigatedTo
(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string msg = "";
if (NavigationContext.QueryString.TryGetValue("msg", out msg))
MyTBl.Text = msg;
}

Visual Basic for SecondPage.xaml.cs

Protected Overrides Sub OnNavigatedTo(ByVal e As System.Windows.Navigation.NavigationEventArgs)
MyBase.OnNavigatedTo(e)
Dim msg As String = ""
If NavigationContext.QueryString.TryGetValue("msg", msg) Then
MyTBl.Text = msg
End If
End Sub

The following illustration displays the home page and second page for the previous example. The string typed into the text box is passed to the second page and displayed in a text block.

home page

 

Tip

For pages that display multiple sections of content, you can display different pieces of content without using navigation by simply re-binding the controls on your page to a new DataContext.

 

Application Bar

The Application Bar is a set of one to four buttons that can be displayed along the bottom of the phone's screen in portrait orientation and along the side in landscape orientation. This is the menu system that is used in Windows Phone, and the buttons in the Application Bar are used to provide users with quick access to an application's most common tasks.

The following illustration shows an Application Bar in Windows Phone, in its expanded state.

Application Bar

The buttons with icons in the Application Bar are called icon buttons. You can have a maximum of four icon buttons. If you try to add more than four an exception will be thrown when your application starts. The ellipsis in the upper-right corner of the Application Bar is used to expand and collapse the Application Bar. The text for the icon buttons appears only if the Application Bar is in its expanded state. You can use the Click event to take action when the user clicks the icon buttons.

In addition to the row of icon buttons, Application Bar can also consist of one or more text-based menu items. These items are displayed in a list that slides up from underneath the icon buttons when the user clicks the ellipsis to the right of the icon buttons or the empty space to the left of icon buttons. In the previous illustration, about and settings are menu items. This menu item list is not hierarchical, so it is not a submenu of any of the icon buttons. Instead, the menu items are used for application actions that are less frequently used and for actions that are difficult to convey with an icon and therefore require a textual representation.

The following illustration shows Application Bars in collapsed and expanded states. and without and with menu items.

Application Bar states

You can add an Application Bar to your Windows Phone application by using the ApplicationBar class. You can add an Application Bar either in XAML or in C#. If you choose to create the Application Bar entirely in XAML, the Windows Phone project template that ships with Windows Phone Developer Tools includes an implementation of an Application Bar in the MainPage.xaml file. All you need to do is uncomment the Application Bar definition and modify the code to use your icon images and menu text.

In the following example the default Application Bar template has been modified to create three icon buttons (new, folders, and sync) and two menu items (settings and add email account).

XAML

<phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
<shell:ApplicationBarIconButton x:Name="newButton"
IconUri="/Images/appbar.new.rest.png" Text="new"
Click="newButton_Click"/>
<shell:ApplicationBarIconButton x:Name="folderButton"
IconUri="/Images/appbar.folder.rest.png" Text="folders"
Click="folderButton_Click"/>
<shell:ApplicationBarIconButton x:Name="syncButton"
IconUri="/Images/appbar.refresh.rest.png" Text="sync"
Click="syncButton_Click"/>
<shell:ApplicationBar.MenuItems>
<shell:ApplicationBarMenuItem Text="settings"/>
<shell:ApplicationBarMenuItem Text="add email account"/>
</shell:ApplicationBar.MenuItems>
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>

The following illustration shows the output for the previous example.

Application Bar

Note that the previous example uses images for icon buttons. For design guidelines about creating Application Bar icon images, and the location of ready-made icons that can be used by your application, see Application Bar Best Practices for Windows Phone.

The Application Bar is not a Silverlight control and doesn't support data binding. This means that the string values used for the button labels must be hardcoded in the XAML and can't be localized. If you plan to localize your application or if you are more comfortable with C#, you can create the Application Bar in code, or use C# to programmatically modify the label values at runtime.

The following example shows how you can create the Application Bar in code. You first create the Application Bar by using the ApplicationBar class. You can then create icon buttons by using the ApplicationBarIconButton class and add those icon buttons to the Application Bar by using the ApplicationBar.Buttons.Add method. You can create menu items by using ApplicationBarMenuItem and add those menu items to the Application Bar by using the ApplicationBar.MenuItems.Add method.

C#

public MainPage()
{
InitializeComponent();
//Create the ApplicationBar
ApplicationBar = new ApplicationBar();
ApplicationBar.IsVisible = true;
ApplicationBar.IsMenuEnabled = true;
//Create the icon buttons and setting its properties
ApplicationBarIconButton newButton = new ApplicationBarIconButton(new Uri
("/Images/appbar.add.rest.png", UriKind.Relative));
newButton.Text = "new";
newButton.Click += new EventHandler(newButton_Click);
ApplicationBarIconButton folderButton = new ApplicationBarIconButton(new Uri
("/Images/appbar.folder.rest.png", UriKind.Relative));
folderButton.Text = "folders";
folderButton.Click += new EventHandler(folderButton_Click);
ApplicationBarIconButton syncButton = new ApplicationBarIconButton(new Uri
("/Images/appbar.sync.rest.png", UriKind.Relative));
syncButton.Text = "sync";
syncButton.Click += new EventHandler(syncButton_Click);
//Add the icon buttons to the Application Bar
ApplicationBar.Buttons.Add(newButton);
ApplicationBar.Buttons.Add(folderButton);
ApplicationBar.Buttons.Add(syncButton);
//Create menu items
ApplicationBarMenuItem settingsMenuItem = new ApplicationBarMenuItem
("settings");
settingsMenuItem.Click += new EventHandler(settingsMenuItem_Click);
ApplicationBarMenuItem addaccountMenuItem = new ApplicationBarMenuItem
("add email account");
addaccountMenuItem.Click += new EventHandler(addaccountMenuItem_Click);
//Add the menu items to the Application Bar
ApplicationBar.MenuItems.Add(settingsMenuItem);
ApplicationBar.MenuItems.Add(addaccountMenuItem);
}

Visual Basic

publicMainPage
{InitializeComponent
'Create the ApplicationBar
ApplicationBar = New ApplicationBar
ApplicationBar.IsVisible = true
ApplicationBar.IsMenuEnabled = true
'Create the icon buttons and set its properties
Dim newButton As ApplicationBarIconButton = New ApplicationBarIconButton(New Uri("/Images/appbar.add.rest.png", UriKind.Relative))
newButton.Text = "new"
AddHandler newButton.Click, AddressOf Me.newButton_Click
Dim folderButton As ApplicationBarIconButton = New ApplicationBarIconButton(New Uri("/Images/appbar.folder.rest.png", UriKind.Relative))
folderButton.Text = "folders"
AddHandler folderButton.Click, AddressOf Me.folderButton_Click
Dim syncButton As ApplicationBarIconButton = New ApplicationBarIconButton(New Uri("/Images/appbar.sync.rest.png", UriKind.Relative))
syncButton.Text = "sync"
AddHandler syncButton.Click, AddressOf Me.syncButton_Click
'Add the icon buttons to the Application Bar
ApplicationBar.Buttons.Add(newButton)
ApplicationBar.Buttons.Add(folderButton)
ApplicationBar.Buttons.Add(syncButton)
'Create menu items
Dim settingsMenuItem As ApplicationBarMenuItem = New ApplicationBarMenuItem("settings")
AddHandler settingsMenuItem.Click, AddressOf Me.settingsMenuItem_Click
Dim addaccountMenuItem As ApplicationBarMenuItem = New ApplicationBarMenuItem("add email account")
AddHandler addaccountMenuItem.Click, AddressOf Me.addaccountMenuItem_Click
'Add the menu items to the Application Bar
ApplicationBar.MenuItems.Add(settingsMenuItem)
ApplicationBar.MenuItems.Add(addaccountMenuItem)

The Application Bar can be defined locally or globally. A local Application Bar can be used only by the page that defines it. This approach is useful if different pages in your application have different tasks. For example, if you're creating an email application, the Inbox page may have tasks such as create new email and sync, and the Compose page may have tasks such as send or delete. So it may make sense to have separate Application Bar for Inbox and Compose pages, and you'll create one Application Bar in the Inbox page and one in the Compose page.

A global Application Bar is one that can be shared across all pages in your application. A global Application Bar is created as an application resource in the App.xaml file. To create a global Application Bar, you typically perform the following steps.

  • Add the XAML definition of the Application Bar to the <Application.Resources> section in the App.xaml file.
  • Add the following attribute within the <phone:PhoneApplicationPage> node of every page where you need the Application Bar:
    ApplicationBar="{StaticResource GlobalAppMenuBar}"

For more information about the Application Bar, see Application Bar for Windows Phone.

Back Button

All Windows Phone devices include a hardware Back button. This button enables the user to navigate back to previous pages in an application and across different applications. For example, you can click a link from your email application to open the web browser, and simply press the hardware Back button to return to your email. This yields a much more consistent user experience across different applications, whether they're third-party applications or part of the Windows Phone's built-in applications. Windows Phone does this by maintaining a journal of your navigation actions to support the Back button functionality. This is also known as back-stack.

The following illustration shows the hardware Back button, Start button, and Search button.

Hardware buttons

You can override the Back button to customize it to do what you want. However, when you do this, you should be certain of what your users consider "back". For example, if you display a pop-up in your application, you might have implemented the Back button to exit the application, but your users might expect it to dismiss the pop-up.

You can override the default Back button behavior by overriding the PhoneApplicationPage.OnBackKeyPress method.

The following example contains a text box. If you type some text in the text box and then press the hardware Back button, a message box is displayed with the message, "You are about to discard your changes. Continue". This behavior is implemented by overriding the PhoneApplicationPage.OnBackKeyPress method.

C#

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
base.OnBackKeyPress(e);
if(MyTB.Text != string.Empty)
{
var result = MessageBox.Show("You are about to discard your changes. Continue?",
"Warning", MessageBoxButton.OKCancel);
if (result != MessageBoxResult.OK)
{
e.Cancel = true;
}
}
}

Visual Basic

Protected Overrides Sub OnBackKeyPress(ByVal e As System.ComponentModel.CancelEventArgs)
MyBase.OnBackKeyPress(e)
If (MyTB.Text <> string.Empty) Then
Dim result As var = MessageBox.Show("You are about to discard your changes. Continue?", "Warning", MessageBoxButton.OKCancel)
If (result <> MessageBoxResult.OK) Then
e.Cancel = true
End If
End If
End Sub

The following illustration displays the result of the previous example. If the user presses the Back button while having text in a text box, a message box is displayed.

back button

Keep the following best practices in mind while overriding the Back button:

  • Consider what "back" means to the user at that point in the application.
  • If the user presses the Back button a second time, you should let the default behavior happen.
  • Try to avoid overusing the Back button for local navigations.
  • To implement transient UI, such as a login screen, use the Silverlight Popup control to display content that partially covers the screen instead of implementing a separate page that requires full navigation. You can add the PhoneApplicationPage.OnBackKeyPress method to your code and set e.Cancel to true (as shown in the previous example) while the pop-up is visible to enable users to use the Back button to close the pop-up.

See Also

var gDomain='m.webtrends.com'; var gDcsId='dcschd84w10000w4lw9hcqmsz_8n3x'; var gTrackEvents=1; var gFpc='WT_FPC'; /*<\/scr"+"ipt>");} /*]]>*/
DCSIMG