In this exercise you will create a new Windows Phone Application project and:
Add appropriate project references
Add an application name as a shared resource string
Edit the main page and add solution folders to hold pages
We will use the Visual Studio 2010 Express for Windows Phone development environment, and will deploy to the Windows Phone Emulator for debugging. The solution we will be working with is based upon the Silverlight for Windows Phone Application template. During development, we will add a Silverlight for Windows Phone project specific item, the Windows Phone Portrait Page.
There is one main Windows Phone Application assembly: Microsoft.Phone.dll. Within this assembly, there are three main two main namespaces to consider:
- Microsoft.Phone.Controls
- Microsoft.Phone.Shell
The MainPage.xaml file, like all PhoneApplicationPage items created from the project item template, contains two grids, named TitlePanel and ContentPanel. Also note that the page controls leverage phone-centric style resources defined in App.xaml.
Note: |
|---|
| The steps in this hands-on lab illustrate procedures using Visual Studio 2010 Express for Windows Phone, but they are equally applicable to Microsoft Visual Studio 2010 with the Windows Phone Developer Tools. Instructions that refer generically to Visual Studio apply to both products. |
The following section provides a little background information about Silverlight navigation and data binding. If you are familiar with these topics, please skip them directly to Task #1.
Note: |
|---|
| The following is a Silverlight navigation overview. |
Silverlight for Windows Phone provides the PhoneApplicationFrame and PhoneApplicationPage classes to facilitate navigation to separate sections of content. PhoneApplicationPage controls represent discrete sections of content. The PhoneApplicationFrame acts as a container for page controls, and facilitates navigation to pages. You create as many different pages as needed to present the content in your application and then navigate to those pages from the frame. You can also enable user-friendly URIs by mapping a particular URI pattern to a file that handles the request for that pattern. To create user-friendly URIs, within a frame, you can specify that a certain URI pattern maps to a particular page.
URI mapping enables you to create a URI that is descriptive of the user action instead of a path to a file. A Uri Mapping can include placeholder segments in the URI that will match any value in that segment. You specify a placeholder segment by enclosing the name of the segment with curly braces ( { and } ). The placeholder segment acts as a variable. The URI request is mapped to the first pattern that matches the request. You can use the HyperlinkButton control to enable users to navigate to pages within the application, by setting the NavigateUri property to a URI that maps to a page. Clicking this causes the hosting frame to navigate to the requested page. The target page can then access placeholder-passed parameters from NavigationContext.QueryString.
URI mapping can be used to provide friendlier routes, obfuscate the physical location of the view, and provide a single view to different navigation parameters (like query strings in HTML). In the following example (not related directly to the current lab) you could see how to “hide” the real physical location of the view (“Home”, “About-Us”), how to implement business navigation logic based on provided value (“Page/{number}”), and how to pass query string parameters to the page that could execute different business logic based on them (“Customers{id}”, “Products/{id}”, “Orders{type}&{id}&{date}”):
<navcore:UriMapper x:Key="TheMapper">
<navcore:UriMapping Uri="Home" MappedUri="/Pages/Views/Default.xaml"/>
<navcore:UriMapping Uri="About-Us" MappedUri="/Pages/Views/Misc/About.xaml"/>
<navcore:UriMapping Uri="Page/{number}" MappedUri="/Pages/Views/Books/Page{number}.xaml"/>
<navcore:UriMapping Uri="Customers/{id}" MappedUri="/Pages/Views/Data/Page.xaml?action=getCustomer&id={id}"/>
<navcore:UriMapping Uri="Products/{id}"
MappedUri="/Pages/Views/Data/Page.xaml?action=getProduct&id={id}"/>
<navcore:UriMapping Uri="Orders/{type}&{id}&{date}" MappedUri="/Pages/Views/Data/Page.xaml?action={type}&orderId={id}&orderDate={number}"/>
</navcore:UriMapper>
Note: |
|---|
| The following is a Data Binding overview. |
Data binding provides a simple way for Silverlight-based applications to display and interact with data. The way data is displayed is separated from the management of the data. A connection, or binding, between the UI and a data object allows data to flow between the two. When a binding is established and the data changes, the UI elements that are bound to the data can reflect changes automatically. Similarly, changes made by the user in a UI element can be reflected in the data object. For example, if the user edits the value in a TextBox, the underlying data value is automatically updated to reflect that change.
Some common binding scenarios include binding a ListBox to a list of headlines, an input form's TextBox to a customer data object, or an Image to the current user's photo
Every binding must specify a source and a target. The following illustration shows the basic concepts of a binding.

Figure 5 Data binding
The binding engine gets information from the Binding object about the following:
- The target UI property that displays and possibly allows user changes to the data. The target can be any DependencyProperty of a FrameworkElement.
- The source object that contains the data that flows between the source and target. The source can be any CLR object, including the target element itself or other UI elements. If the target is in a data template, the source can be the UI element to which the template is applied.
- The direction of the data flow. The direction is specified by setting the Mode property on the Binding object.
- The optional value converter that applies to the data as it is passed. The value converter is a class that implements IValueConverter.
For example, the Foreground property of a TextBox can be bound to a SolidColorBrush so that the color of the text can change based on the data. In this scenario, the Foreground property is the target, and the SolidColorBrush object is the source for the binding.
A data template allows you to specify how data is displayed. For example, your object might contain an image and a string. You could define the data template to display the string on the right of the image, the left, or overlay the image. You can add margins between the image and text, a border, or background color with data templates. In addition, you can apply the same data template to all the objects in your collection when using an ItemsControl (like ListBox).
Task 1 – Creating a Windows Phone Application Project in Visual Studio
During this task you will create a new Windows Phone Application and explore its structure.
Note: |
|---|
| If you are already familiar with creating new projects using Visual Studio, or you did some any of the other Windows Phone labs, you can create a new Windows Phone Application project named WindowsPhoneNavigationAndControls and skip the following steps and go directly to step 10. |
- Open Microsoft Visual Studio 2010 Express for Windows Phone from Start | All Programs | Microsoft Visual Studio 2010 Express | Microsoft Visual Studio 2010 Express for Windows Phone.
Note:Visual Studio 2010: Open Visual Studio 2010 from Start | All Programs | Microsoft Visual Studio 2010. - In the File menu, choose New Project.
Note:Visual Studio 2010: In the File menu, point to New and then select Project. - In the New Project dialog, select the Windows Phone category in the list of installed templates, and then set the project name to
WindowsPhoneNavigation and solution name to Begin, and click
OK.

Figure 6 Creating a new Windows Phone application project in Visual Studio 2010 Express for Windows Phone
- In Solution Explorer, review the structure of the solution generated by the
Windows Phone Application template. A Visual Studio solution functions as a container for specific project types. In this case, it contains a single
Windows Phone project named WindowsPhoneNavigation.

Figure 7 Solution Explorer showing the WindowsPhoneNavigation application
Note:Solution Explorer allows you to view items and perform item management tasks for a solution or a project. To show Solution Explorer, press CTRL + W, S or in the View menu, select Other Windows | Solution Explorer. The WindowsPhoneNavigation project contains the following items:
Item
Description
App.xaml / App.xaml.cs
Defines the entry point of the application, initializes application-scoped resources, and displays the application user interface
MainPage.xaml / MainPage.xaml.cs
Defines a page with the user interface of the application
ApplicationIcon.png
An image file with an icon that represents the application icon in the phone’s application list
Background.png
An image file with an icon that represents the application icon in the start screen
SplashScreenImage.jpg
This is the image that will first be displayed when the application launches. The splash screen gives the user immediate feedback that the application is launching and will remain displayed until the navigation to the first page has been completed. Your splash screen can look similar to your first page in order to give the appearance that the application is loading quickly.
Properties\AppManifest.xml
An application manifest file required to generate the application package
Properties\AssemblyInfo.cs
Contains the name and version metadata that is embedded into the generated assembly
Properties\WMAppManifest.xml
Metadata that contains phone application information like title, icon location, capabilities, etc.
References folder
List of libraries (assemblies) that provide services and functionality that the application requires in order to work
- First, right-click App.xaml in Solution Explorer and choose
View Designer. Notice that the file contains XAML markup with an Application root element and inside it an
Application.Resources section. Herein you can define application-level resources such as colors, brushes and style objects used throughout the application.
The XAML code also initializes the ApplicationLifetimeObjects property of the Application to create a PhoneApplicationService object. The PhoneApplicationService class provides access to various aspects of the application’s lifetime. This includes management of the application’s idle behavior and management of the application’s state when it becomes active or inactive.

Figure 8 Default App.xaml file generated by the Windows Phone application template
Note:The App.xaml file, together with its code-behind file App.xaml.cs, defines an instance of the Application class. This class encapsulates a Windows Phone application and provides its entry point. - Now, right-click App.xaml in Solution Explorer and choose View Code to open its code-behind file. Notice that, in its constructor, this
Application-derived class already subscribes a handler for the UnhandledException event.
The RootFrame property in the Application class identifies the starting page of the application. All Windows Phone applications have a single top-level container element whose data type is PhoneApplicationFrame. The frame hosts one or more PhoneApplicationPage elements that present content for the application. It also handles navigation between pages.

Figure 9 Application code-behind file showing global event handlers
Note:The Application class, generated by the Windows Phone application template, also include handlers for the Launching and Closing events, among others. You can update these methods to execute custom code when the Windows Phone application launches and closes. - The generated project includes a default document that contains XAML markup that defines the main UI of the application. To view this file in the designer, double-click
MainPage.xaml in Solution Explorer.
By default, the designer shows the document in split view, with one pane displaying the XAML markup and the other one showing a design view with a WYSIWYG representation of the user interface elements. Except for those elements included by the template to display an application name and title, which you can remove if you do not require them, the XAML document provides a blank canvas to which you can add controls to create the user interface of your application.

Figure 10 XAML designer showing the main user interface of the application
Note:Extensible Application Markup Language (XAML) is a declarative language. You can create visible user interface (UI) elements in the declarative XAML markup. You can then use a separate code-behind file to respond to events and manipulate the objects you declared in XAML. An XML-based declarative language is very intuitive for creating interfaces from prototype to production, especially for people with a background in Web design and technologies. - The ApplicationIcon.png file contains the icon that identifies the application in the quick launch screen of the phone device. You can double-click the item in
Solution Explorer to open the file in a registered application in your machine that can edit image files, for example,
Paint.exe.
Note:Visual Studio 2010: In Visual Studio 2010, double-clicking the icon file in Solution Explorer opens the built-in image editor. - A Windows Phone application typically takes advantage of services provided by the underlying platform or by other libraries. To use this functionality, the application needs to reference the corresponding assemblies that implement these services. To display
the assemblies referenced by the project, expand the References node in
Solution Explorer and examine the list. It contains regular Silverlight assemblies as well as assemblies specific to the
Windows Phone platform.

Figure 11 Solution Explorer showing the assemblies referenced by the project
- Open App.xaml (if closed) and add the following blue-highlighted clr-namespace declaration for the System CLR namespace within the Application tag (located at the top of the file).
<Application x:Class="WindowsPhoneNavigation.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:system="clr-namespace:System;assembly=mscorlib"> ... </Application>
Note:The clr-namespace declaration is needed to introduce the namespace defined in .NET assembly. You can map XML namespaces to assemblies using a series of tokens within an xmlns prefix declaration, similar to how the standard Silverlight and XAML namespaces are mapped to prefixes. The syntax takes the following possible named tokens and values: clr-namespace: The common language runtime (CLR) namespace declared within the assembly that contains the public types to expose as elements. assembly= The assembly that contains some or all of the referenced CLR namespace. This value is typically just the name of the assembly, not the path, and does not include the extension (such as .dll or .exe). The path to that assembly must be established as a project reference in the project file that contains the XAML you are trying to map. In order to incorporate versioning and strong-name signing, the assembly value can be a string as defined by AssemblyName, rather than the simple string name. - Now let’s add a shared string to the application resources that we can reference from all XAML pages in the application. Copy the following highlighted code into
Application.Resources element.
<Application.Resources> <system:String x:Key="AppName">CONTROLS & NAVIGATION</system:String> </Application.Resources>
- Open MainPage.xaml and locate the TitlePanel.
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"> <TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/> <TextBlock x:Name="PageTitle" Text="page name" Margin="-9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/> </StackPanel> - Change the text value of the ApplicationTitle and the PageTitle elements as shown below:
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"> <TextBlock x:Name="ApplicationTitle" Text="{StaticResource AppName}" Style="{StaticResource PhoneTextNormalStyle}"/> <TextBlock x:Name="PageTitle" Text="Main Page" Margin="-9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/> </StackPanel> - Press F5 to launch the application in the Windows Phone Emulator. Notice that a device emulator window appears and there is a pause while Visual Studio sets up the emulator environment and deploys the image. Once it is ready, the emulator
shows the Start page and shortly thereafter, your application appears in the emulator window.

Figure 12 Running the application in the Windows Phone Emulator
- Until you create the user interface and program the application logic, there is very little that you can do with the application. Press
SHIFT + F5 or click the Stop button in the toolbar to detach the debugger and end the debugging session.
Do not close the emulator window.

Figure 13 Ending the debugging session
Note:When you start a debugging session, it takes a perceptible amount of time to set up the emulator environment and launch the application. To streamline your debugging experience, avoid closing the emulator while you work with the source code in Visual Studio. Once the emulator is running, it takes very little time to stop the current session, edit the source code, and then build and deploy a new image of your application to start a new debugging session. - Add three new project folders (Views, Misc, and Assets) to hold elements for display on the phone pages:
- Right-click on the project name.
- Select Add | New Folder.
- Name the new project folder Views.
- Repeat this two more times, and name the second folder Misc and the third folder Assets.

Figure 14 Adding New Project Folder
- Right-click on the Views folder and create the following subfolders beneath it:
- About
- Music
- Pictures
- Video
- WebBrowser
- Right-click on the Assets folder and create a subfolder beneath it named
Images.
Note:To create a subfolders, right-click on the parent folder (in this case Assets) and follow the same steps you followed to create the Views folder. - The completed project structure should look :

Figure 15 Completed project structure
Add existing assets from the provided assets folder. The Assets folder is located in the lab root install path (referenced as [{LAB_PATH}\Assets])
Note:To add an existing item, right-click on the desired folder, and select Add | Existing Item. After Add Existing Item pops-up, browse to desired location, select items (multiple selection is supported) and click the Add button. 
Figure 16 Adding existing items to project folders
Asset Location
Asset Name
Project Folder
{LAB_PATH}\Assets\Classes
Photo.cs
Utils.cs
\Misc
{LAB_PATH}\Assets\Music
Music1.mp3
Music2.mid
\Assets
{LAB_PATH}\Assets\Video
Video1.wmv
Video2.wmv
\Assets
{LAB_PATH}\Assets\Pictures
All the pictures
\Assets\Images
{LAB_PATH}\Assets\Icons
Ie_Icon.png
Pictures_Icon.png
\ (root project folder)
- Silverlight supports different types of resources: Embedded, Content, and Site of Origin. Embedded resources are compiled into the assembly; content resources are added into the application package (XAP file), and site of origin resources are referenced from their original location. In this lab all resources will be content resources.
- Change all added assets (except .cs files) to be content resources:
- Right-click the resource file (for example, Pictures_Icon.png).
- Select Properties.
- Select Content.
- Repeat for all of the resource files other than the .cs files.

Figure 17 Changing resource type
- After completing this step, the project structure should look like:

Figure 18 Completed project structure
Note:The images filenames and number could vary from provided screenshot.
During this task you created a new Windows Phone Application solution using templates provided by Visual Studio 2010 Express for Windows Phone and added some assets provided with the lab to the application. In addition you explored how to execute the application using Windows Phone emulator.
Task 2 – Adding Pages and Navigating between them
In this task you will add some pages and modify them. These pages will be used later for playing back selected music and video files, displaying Web content, etc. Following this, we will add Navigation support to the application along with a HyperlinkButton to the MainPage for accessing navigation.
The Application.RootVisual (located in App.xaml file) is a PhoneApplicationFrame – it will contain a collection of UriMappings which we will add in this exercise.
- Under the Views\Music folder, add a new project item, Windows Phone Portrait Page:
- Right-click the Music folder.
- Select Add | New Item.
- Select Windows Phone Portrait Page.
- Name it Default.xaml.

Figure 19 Add New Item dialog box
- Open the newly created page (if not opened automatically).
- In the XAML page, locate the TitlePanel section and change it to following:
<Grid Grid.Row="0" x:Name="TitlePanel" Margin="12,17,0,28"> <TextBlock x:Name="ApplicationName" Text="{StaticResource AppName}" Style="{StaticResource PhoneTextNormalStyle}"/> <TextBlock x:Name="ListName" Text="Music" Style="{StaticResource PhoneTextTitle1Style}"/> </Grid> - Follow steps 1 through 3 to create a new Windows Phone “Video” Page in the
Video folder.
Note:The page name should be also Default.xaml, but the text on page should be “Videos” instead of “Music” - Follow steps 1 through 3 to create a new Windows Phone “About” Page in the
About folder.
Note:The page name should be also Default.xaml, but the text on page should be “About” instead of “Music” - Modify the About page by adding the following markup inside ContentPanel.
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <TextBlock TextWrapping="Wrap" Margin="5" Style="{StaticResource PhoneTextNormalStyle}" Text="This is a sample Windows Phone 7 navigation application. All rights reserved to you - you, the writer of this lab!"/> </Grid> - Next you will modify MainPage.xaml and add a number of HyperlinkButton controls for navigating to the created pages. Open
App.xaml, and locate the AppName resource created in previous task. Add the following code below.
<Application.Resources> <system:String x:Key="AppName">CONTROLS & NAVIGATION</system:String> <!-- Hyperlink style --> <Style x:Key="PhoneHyperlinkStyle" TargetType="HyperlinkButton"> <Setter Property="Margin" Value="30,10,0,10"/> <Setter Property="Foreground" Value="{StaticResource PhoneAccentBrush}" /> <Setter Property="HorizontalAlignment" Value="Left" /> </Style> </Application.Resources> - Open App.xaml file and Introduce a new namespace to the application by adding following line within the Application tag (for example after
xmlns:system attribute, before the tag closure).
<Application x:Class="WindowsPhoneNavigation.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:system="clr-namespace:System;assembly=mscorlib" xmlns:nav="clr-namespace:System.Windows.Navigation;assembly=Microsoft.Phone" > ... </Application>
- Now locate the Application.Resources element and add the UriMapper object as follows. This will define an
UriMapper object that will be used through the entire application for all navigation process.
<Application.Resources> ... <nav:UriMapper x:Key="UriMapper"> <nav:UriMapper.UriMappings> <nav:UriMapping Uri="/Music/{song}" MappedUri="/Views/Music/Default.xaml?Song=Assets/{song}"/> <nav:UriMapping Uri="/Video/{video}" MappedUri="/Views/Video/Default.xaml?Video=Assets/{video}"/> <nav:UriMapping Uri="/WebBrowser/{defaultURL}" MappedUri="/Views/WebBrowser/Default.xaml?DefaultURL={defaultURL}"/> <nav:UriMapping Uri="/Pictures" MappedUri="/Views/Pictures/Default.xaml"/> <nav:UriMapping Uri="/PictureView/{picture}" MappedUri="/Views/Pictures/PictureView.xaml?Picture={picture}"/> <nav:UriMapping Uri="/About" MappedUri="/Views/About/Default.xaml"/> </nav:UriMapper.UriMappings> </nav:UriMapper> </Application.Resources>
Note:Here the URI mapping used to “hide” real navigation structure and provide query string parameters to the pages. - For the UriMapper object to be used through the application you now need to set the object in the Resources dictionary to the application’s RootFrame. Right-click
App.xaml in Solution Explorer and choose View Code to open its code-behind file. Add the following blue-highlighted line to the class constructor:
public App() { // Global handler for uncaught exceptions. UnhandledException += Application_UnhandledException; ... // Standard Silverlight initialization InitializeComponent(); // Phone-specific initialization InitializePhoneApplication(); this.RootFrame.UriMapper = Resources["UriMapper"] as UriMapper; }
Note:The Application Resources can be accessed from code as a string-keyed dictionary, using the x:Key property (in this case “UriMapper”) as the access key. - Open MainPage.xaml, locate ContentPanel and add the following markup inside.
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <ScrollViewer BorderBrush="Transparent"> <StackPanel Margin="5"> <TextBlock Text="Music" Style="{StaticResource PhoneTextGroupHeaderStyle}"/> <HyperlinkButton NavigateUri="/Music/Music1.mp3" Content="Song #1" Style="{StaticResource PhoneHyperlinkStyle}" /> <HyperlinkButton NavigateUri="/Music/Music2.mid" Content="Song #2" Style="{StaticResource PhoneHyperlinkStyle}" /> <TextBlock Text="Videos" Style="{StaticResource PhoneTextGroupHeaderStyle}"/> <HyperlinkButton NavigateUri="/Video/Video1.wmv" Content="Video #1" Style="{StaticResource PhoneHyperlinkStyle}"/> <HyperlinkButton NavigateUri="/Video/Video2.wmv" Content="Video #2" Style="{StaticResource PhoneHyperlinkStyle}"/> <TextBlock Text="About" Style="{StaticResource PhoneTextGroupHeaderStyle}"/> <HyperlinkButton NavigateUri="/About" Content="About" Style="{StaticResource PhoneHyperlinkStyle}"/> </StackPanel> </ScrollViewer> </Grid> - At this stage the Visual Studio design surface should look like:

Figure 20 Design surface state
- Compile and run the application. Click hyperlinks to ensure that everything works correctly.
Note:Use the Back button to get back to the applications’ main page. 
Figure 21 Running the solution
- This step concludes the first exercise. During this exercise you created a simple Windows Phone Silverlight application, added multiple resources and pages to this application and created navigation between those pages. In the next Exercise, you will add
user controls to the created pages.
Note:The solution for this exercise is located at the Source\Ex1-IntroductionToPhoneNavigationModel\End folder of this lab.