Today in this Windows Phone 7 Tutorial, we will discuss on Navigation Service and Navigation Context. We will create a small demo application to showcase the functionality of those class. We will navigate from one page to another and then again use the history to return back to the previous page.

 

In this chapter, we will use a case study of showing customer details in multiple page and using that demo we will learn about Navigation in Windows Phone 7 series. Read to learn more on it. Source code is available at the end of the post.

 

Index - Windows Phone 7 (Mango) Tutorial

 

Background

Hope, you read my previous chapters of the Windows Phone 7 Tutorial series and learnt about basic of Navigation Service and Navigation Context present in the base page. If you didn't read them, follow the below links to read those first. Also, below are the links from where you can download the Windows Phone Developer Tools 7.1 (Mango) public beta. Explore the new features available in Windows Phone 7.1 too from the below links:

Once you are ready with the development environment and created the Windows Phone Application project, it's time to know about the basic about the navigation service and navigation context from the above links. Then jump into our demo project setup and start learning on Windows Phone Navigation mechanism.

 

 

Preparing Project

Once you create the "Windows Phone Application" project, add two new items (Windows Phone Page) in the solution. To do this, right click on the project and Add New Item. From the dialog chose your page. In our case, we will add a "Windows Phone Portrait Page". Assign a proper name and click "OK" to continue.

 

We will follow this step to create two Phone Page named "CustomerListPage.xaml" and "CustomerDetailsPage.xaml".

 

image

 

 

Once done, you will see the added two XAML pages in your project as shown below:

 

image

 

Just do a build to make sure that it builds fine. If you get any error, solve it first before jumping to the next step.

 

 

Create Data Service

Before doing anything with the XAML and code, we need to create a mocked data service, which will return a collection of Customer. Let's create a class called "CustomerService" and implement two methods named "GetCustomerList()" and "GetCustomer(id)".

 

The first method will return customers list and the second method will return the Customer based on the supplied customer id. Here is the code snippet of the same:

 

 
public static ObservableCollection<Customer> GetCustomerList()
{
    return m_customerCollection;
}
 
public static Customer GetCustomer(string id)
{
    return m_customerCollection.Where(customer =>
                                        customer.Id.Equals(id)).FirstOrDefault();
}

 

 

Here we used the following Customer class which has some properties called "Id", "Firstname", "Lastname" and "City". The class implementation is as below:

 

 
namespace NavigationDemo.Services
{
    public class Customer
    {
        public string Id { get; set; }
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public string City { get; set; }
    }
}

 

You can also download the source code from the download section of this chapter.

 

 

Main Page Implementation

Now we will design our MainPage.xaml. There we will add a HyperlinkButton in the content panel. When user clicks on the button, it will navigate him to the CustomerListPage.xaml file. Set the proper NavigateUri to the hyperlink button.

 

Find the XAML code of the MainPage.xaml here:

 
<!--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 Demo" 
                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"
        VerticalAlignment="Top">
    <HyperlinkButton Content="Show Customer List" NavigateUri="/CustomerListPage.xaml"/>
</Grid>

 

This will load the following UI in the Phone page view:

 

image

 

There "Show Customer List" is the hyperlink button. Once you click on this link, it will redirect you to the Customer List Page as mentioned in the XAML code.

 

 

Customer List Page Implementation

Our code now redirects the user click in the Home page to the CustomerListPage.xaml but we don't have any content there to load. Hence, let us design the XAML page with a ListBox where we will load the customer list. To do this, we need to create a Customers property of type ObservableCollection<Customer> and make sure that you are creating a Dependency Property.

 

Now bind the dependency property to the ListBox added to the CustomerListPage.xaml file. Set DisplayMemberPath property to "Firstname" and SelectedValuePath property to "Id", so that, it will display the customers first name and returns the selected value as Id of the customer. Also, register the SelectionChanged event for the ListBox.

 

Find the implemented XAML code here:

 
<!--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 Demo"
                Style="{StaticResource PhoneTextNormalStyle}"/>
    <TextBlock x:Name="PageTitle" Text="Customer List" 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">
    <ListBox x:Name="customerList"
                SelectedValuePath="Id" DisplayMemberPath="Firstname"
                ItemsSource="{Binding Customers, ElementName=phonePage}" 
                HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
                SelectionChanged="CustomerList_SelectionChanged"/>
</Grid>

 

 

This will populate the customer list in the Listbox when the page loads in the UI. Find below the screenshot of the implemented demo page. Now we need to implement the feature such that, if user clicks on the customer name, it will redirect you to the CustomerDetailsPage.xaml with selected customer details.

 

image

 

To do this, let's implement the SelectionChanged event. This time we will show the navigation from the code. If you are familiar with Silverlight, this step is easy for you.

 

In the event implementation, we will use the NavigationService present in the page level of any phone application. If you are not familiar with the Page class, you can read it here: Windows Phone 7 (Mango) Tutorial - 2 - Know more about Page.

 

 
private void CustomerList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    NavigationService.Navigate(new Uri("/CustomerDetailsPage.xaml?id=" +
                                       customerList.SelectedValue,
                                       UriKind.RelativeOrAbsolute));
}

 

As shown above, we will call the Navigate() method of the NavigationService and pass the proper Uri to it. Notice that, we used query string paramter to pass the id of the customer to the details page. Now, it's the job of the details page to load the proper record based on the passed id.

 

 

Customer Details Page Implementation

It's time to create proper UI for the details page where we will load the customer information. In our example, we will display firstname, lastname and the city of the customer. Before that, create a dependency property named "Customer" in the code behind. Now add a stackpanel in the XAML which contains a TextBlock which displays Firstname, Lastname and City of the customer. We will also add a button for the back button implementation.

 

Remember that, it is not require to create a back button in the Windows Phone application, as it already has a back button in the hardware level. But to demonstrate the NavigationService behavior we will add such button in the UI.

 

Find the XAML code of the customer details page here:

 
<!--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 Demo"
                Style="{StaticResource PhoneTextNormalStyle}"/>
    <TextBlock x:Name="PageTitle" Text="Details 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">
    <StackPanel>
        <TextBlock DataContext="{Binding Customer, ElementName=phonePage}">
            <Run Text="{Binding Firstname}"/>
            <Run Text="{Binding Lastname}"/>
            <LineBreak/>
            <Run Text="{Binding City}"/>
        </TextBlock>
        <Button Content="Back" 
                Margin="20"
                Width="150" Height="80"
                HorizontalAlignment="Center"
                Click="BackButton_Clicked"/>
    </StackPanel>
</Grid>

 

 

Come to the code behind now and override the OnNavigatedTo() event. There use NavigationContext to retrieve the query string parameter. As shown in the below code, pass the customer id which we retrieved from the query string parameter and pass it to the CustomerService.GetCustomer() method. This will return the respective customer details to you based on the customer id.

 
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
 
    string id = NavigationContext.QueryString["id"];
    Customer = CustomerService.GetCustomer(id);
}
 
private void BackButton_Clicked(object sender, RoutedEventArgs e)
{
    if (NavigationService.CanGoBack)
    {
        NavigationService.GoBack();
    }
}

 

As shown in the above code, we also implemented the back button click event. In the event implementation, we will check for the property called "CanGoBack" from the Navigation service. This will return whether a history back is possible. If true, we called the GoBack() method from the same NavigationService.

 

image

 

This implements the history back functionality to the button. Once you run the application and click the desired customer name in the customer list page, you will be redirected to the details page and you will see the respected customer information in the UI.

 

You can also click the back button. This will return you to the list page. Select a different customer name and this will load the proper value in the details page as shown in the above screenshot.

 

 

Download Source Code

You can download the source code of the above demo application freely from the below link:

 

Hope this will help you to understand the functionality of Navigation service and Navigation context of the Windows Phone page API. Stay tuned for the next chapter of the tutorial series on Windows Phone 7 with Mango. Till then happy coding. Don't forget to share this to your friends and followers. Feedback and Suggestions are always welcome. If you have any queries, let me know. I will try to answer you as early as possible.

Have a question? Or, a comment? Let's Discuss it below...

dhgate

Thank you for visiting our website!

We value your engagement and would love to hear your thoughts. Don't forget to leave a comment below to share your feedback, opinions, or questions.

We believe in fostering an interactive and inclusive community, and your comments play a crucial role in creating that environment.