Windows Phone 7 (Mango) Tutorial - 6 - Working with Navigation



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.

13 comments

  1. your tutorial series are awesome and very helpful for a beginner. keep going and thanks for sharing.

    ReplyDelete
  2. Hi Kunal -- I tweaked this example a bit (mostly renaming) to make sure if I understand all that is being done. In my version, the ListBox is not getting displayed (or showing up empty?) I am a little new to C#/LINQ. Any suggestions how I might go abount debugging the problem. I verified that ListPage.xaml.cs does get a list returned from service.cs. So, I guess the problem is with datasource binding. I eye-balled it many times, but nothing seems to jump out.

    Thanks.
    Neo

    ReplyDelete
  3. Never mind. Found the problem. Was a typo in the ListBox ItemSource value.

    Neo

    ReplyDelete
  4. Wow, that's cool that you found the solution.

    ReplyDelete
  5. Hi Kunal! I downloaded the source code but unfortunatly, it didn't work ;)

    ReplyDelete
  6. Can you tell me what issue are you facing? Is there any error?
    BTW, I created this demo with Windows Phone 7 Beta. Probably, you may check the APIs in final release.

    ReplyDelete
  7. Hi Kunal
    I tried this example in my version and the ListBox is displaying nothing. I verified all the pages and it seems to the problem of datasource binding. I checked the code many times, but the ListBox is still empty.

    Thanks.
    Fan

    ReplyDelete
  8. It can have only one issue: the binding is wrong. Check the ElementName and make sure that you declared the page name, which you are referring as ElementName.

    ReplyDelete
  9. Hi, I'm confused on how the elementname and phonepage are working ? Also, this is another topic but can you explain me what _Customer for example is ? Like using the _ infront of a variable

    ReplyDelete
  10. hi kunal can u give me a solution for navigating to html page in windows phone

    ReplyDelete
  11. kunal from where r u entering the data ??

    ReplyDelete
    Replies
    1. Hi Raman,

      For this demo solution, I hardcoded the data in the class file. You can check it by downloading the sample project.

      Delete
  12. Hey Kunal

    I'm *NEW* to windows phone programming and like I said I just stumble unto to your site. I'm having a problem creating a class. I know it might sound stupid but I'm a newbie to this whole programming world. Please advise.

    ReplyDelete


 
© 2008-2014 Kunal-Chowdhury.com | Designed by Kunal Chowdhury
Back to top