You are on page 1of 62

Hands-On Lab

Hello Windows Phone


Lab version: 1.1.0
Last updated: 11/1/2010
Hello Windows Phone Hands-on Lab

CONTENTS

OVERVIEW ................................................................................................................................................... 3

EXERCISE 1: CREATING WINDOWS PHONE APPLICATIONS WITH MICROSOFT VISUAL STUDIO


2010 EXPRESS FOR WINDOWS PHONE .................................................................................................. 6
Task 1 – Creating a Windows Phone Application Project in Visual Studio ........................................... 6
Task 2 – Building and Testing the Application in the Windows Phone Emulator ............................... 15
Task 3 – Designing the User Interface................................................................................................. 20
Task 4 – Handling Events from the User Interface.............................................................................. 26
Task 5 – Verification ............................................................................................................................ 28

EXERCISE 2: USING EXPRESSION BLEND TO DESIGN THE UX OF YOUR WINDOWS PHONE


APPLICATION ............................................................................................................................................ 34
Task 1 – Creating a Custom Button in Expression Blend .................................................................... 34
Task 2 – Adding Visual States to the Custom Control ......................................................................... 47
Task 3 – Creating an Animation for the Banner Text .......................................................................... 51
Task 4 – Verification ............................................................................................................................ 60

SUMMARY .................................................................................................................................................. 61

Page | 2
Hello Windows Phone Hands-on Lab

Overview

This lab intends to be the classic “Hello World” application, introducing you to the tools and procedures
required to build and test Silverlight for Windows Phone applications. The Windows Phone Application
Platform enables:

 Awesome applications and games. Use Silverlight and XNA frameworks to craft interactive,
compelling, high-quality applications and games for the Windows Phone 7.
 Fast, high quality, and feature-rich applications. The combination of Visual Studio 2010 and
Expression Blend with standardized Windows Phone 7 hardware specifications means more
time is available for you to make your vision real on every device.
 Bigger opportunities. Better partnerships. Build exciting applications and games with your
current skills and tools for Windows Phone 7, and reach customers no matter what device they
use. Windows Phone Marketplace takes care of sales and distribution so you don’t have to.
Code and collect!

During the course of the lab, you will see how to use Microsoft Visual Studio 2010 Express for Windows
Phone and Expression Blend to build and design your Windows Phone applications. Visual Studio
provides an environment oriented towards application developers whereas Expression Blend is more
suited to user experience (UX) designers. The tools complement each other and enable extensive
designer/developer collaboration.
This lab demonstrates a typical development scenario, where you initially create application logic and
lay out pages and controls for your Windows Phone application in Visual Studio, and then design the
user experience using Expression Blend by applying styles and animations to pages and controls. In this
lab, you learn about the structure of a Windows Phone application and find out how to use Extensible
Application Markup Language (XAML) to create the user interface (UI) for your application. XAML is a
declarative language; it's the primary format for declaring a Silverlight UI and the elements in that UI.
Finally, you learn how to deploy and debug your Windows Phone application on the Windows Phone
Emulator.

Objectives
The audience for this lab is developers who are less familiar with Microsoft tools, such as Visual Studio,
and are relatively new to Silverlight. If you are comfortable with the Silverlight programming model and

Page | 3
Hello Windows Phone Hands-on Lab

already work with Visual Studio and the Microsoft Expression suite, you may consider skipping this lab.
On the other hand, if you are completely new to Silverlight, we highly recommend that you enrich your
Silverlight skills by first reviewing some Silverlight labs that can be found at http://silverlight.net/learn/.
In this hands-on lab, you will:
 Become familiar with the Windows Phone Developer Tools: Microsoft Visual Studio 2010
Express for Windows Phone and Windows Phone Emulator. These tools are all you need to
create and test any managed Windows Phone application.

 Use Microsoft Expression Blend for Windows Phone to enhance the user experience of your
application by applying styles and animations.
 Learn the structure underlying a Silverlight for Windows Phone application and the differences
between Silverlight and Silverlight for Windows Phone.

 Write, test, deploy, and debug your Silverlight for Windows Phone application using Microsoft
Visual Studio 2010 Express for Windows Phone and the Windows Phone Emulator.

Prerequisites
The following are required to complete this hands-on lab:

 Microsoft Visual Studio 2010 Express for Windows Phone or Microsoft Visual Studio 2010
 Microsoft Expression Blend for Windows Phone or Microsoft Expression Blend 4 with Microsoft
Expression Blend Add-In for Windows Phone
 Windows Phone Developer Tools

Note: All of these Tools can be downloaded together in a single package from
http://developer.windowsphone.com

Exercises
This hands-on lab includes the following exercises:
1. Creating Windows Phone Applications with Microsoft Visual Studio 2010 Express for Windows
Phone
2. Using Expression Blend to Design the UX for your Windows Phone Application

Page | 4
Hello Windows Phone Hands-on Lab

Estimated time to complete this lab: 45 minutes.

Page | 5
Hello Windows Phone Hands-on Lab

Exercise 1: Creating Windows Phone


Applications with Microsoft Visual
Studio 2010 Express for Windows Phone
In this exercise, you will create, test, deploy and run your first “Hello World” Silverlight for Windows
Phone application. You will learn how to use the Windows Phone Developer Tools including the free
Microsoft Visual Studio 2010 Express for Windows Phone IDE, and the Windows Phone Emulator.
During the exercise, you will create a new Silverlight for Windows Phone project. You start with the very
basic elements of any Windows Phone application, adding basic button and text handling to the default
Windows Phone project template. Since this is a Silverlight for Windows Phone application, you need to
follow the Silverlight programming model and define your user interface using XAML. Although it is
possible to develop an XAML-based UI using any code, it is much easier to express yourself and take
advantage of good and easy tooling when you work with XAML.
To build user interfaces for the Windows Phone using XAML, you edit the XAML of the main page to add
three elements: a text box, a button, and a text block. These Silverlight controls have been ported to
work in the Silverlight for Windows Phone runtime environment. Once completed, the application
allows you to enter a text message in the text box and then click the button to display the text you
entered in the text block.
Finally, once the code is ready, you build the application and deploy it to the Windows Phone Emulator
to test it. To debug applications running in the emulator, you set up a breakpoint and use the debugger
to step through the source code and examine the value of the program variables.

Note: The steps in this hands-on lab illustrate procedures using Microsoft 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.

Task 1 – Creating a Windows Phone Application Project in Visual Studio


In this task, you use a predefined template in Microsoft Visual Studio 2010 Express for Windows Phone
to create a Silverlight for Windows Phone Application project that you can use as the starting point for
your first application.

Page | 6
Hello Windows Phone Hands-on Lab

1. 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.

Visual Studio 2010: Open Visual Studio 2010 from Start | All Programs | Microsoft Visual
Studio 2010.

2. In the File menu, choose New Project.

Visual Studio 2010: In the File menu, point to New and then select Project.

3. In the New Project dialog, select the Silverlight for Windows Phone category in the list of
installed templates, and there the Windows Phone Application template. Then set the name to
HelloPhone and the location to Ex1-CreatingWP7AppsWithVisualStudio in the Source folder of
the lab. Change the solution name to Begin, and then click OK.

Figure 1
Creating a new Windows Phone application project in Microsoft Visual Studio 2010 Express for
Windows Phone

Page | 7
Hello Windows Phone Hands-on Lab

4. In Solution Explorer, review the structure of the solution generated by the Windows Phone
Application template. Any Visual Studio solution is a container for related projects; in this case,
it contains a single Silverlight for Windows Phone project named HelloPhone.

Figure 2
Solution Explorer showing the HelloPhone application

Note: Solution Explorer allows you to view items and perform item management tasks in a
solution or a project. To show Solution Explorer, press CTRL + W, S or in the View menu, select
Other Windows | Solution Explorer.

The HelloPhone 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 / Defines a page with the user interface of the application


MainPage.xaml.cs

ApplicationIcon.png An image file with an icon that represents the application icon in the
phone’s application list

Page | 8
Hello Windows Phone Hands-on Lab

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 A manifest file that includes specific metadata related to a Windows


Phone Silverlight application, including specific features available only
for Silverlight for Windows Phone

References folder A list of libraries (assemblies) that provide services and functionality
that the application requires to work

5. 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.

Page | 9
Hello Windows Phone Hands-on Lab

Figure 3
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 Silverlight for Windows Phone application and
provides its entry point.

6. 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.

Page | 10
Hello Windows Phone Hands-on Lab

Figure 4
Application code-behind file showing global event handlers
Page | 11
Hello Windows Phone Hands-on Lab

Note: The Application class, generated by the Silverlight for 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.

7. 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. One pane displays the XAML markup
and the other one shows 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 add controls to create your application’s user interface.

Figure 5
XAML designer showing the main user interface of the application

Page | 12
Hello Windows Phone Hands-on Lab

Note: Extensible Application Markup Language (XAML) is a declarative language. You can
create visible 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 XAML-
based declarative language is very intuitive for creating interfaces from prototype to
production, especially for people with a background in Web design and technologies.

8. 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 image editing application on your machine, for example, Paint.exe.

Note: In Visual Studio 2010, double-clicking the icon file in Solution Explorer opens the built-in
image editor.

9. 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.

Page | 13
Hello Windows Phone Hands-on Lab

Figure 6
Solution Explorer showing the assemblies referenced by the project

10. The project’s Properties window is the only way to edit the WP manifest file, as shown in the
following figure. To open this window, right-click the HelloPhone project in the Solution
Explorer and select Properties.

Page | 14
Hello Windows Phone Hands-on Lab

Figure 7
Project Properties window

Note: The Windows Phone project properties window allows you to modify some phone-
specific properties. These properties relate to the deployment and appearance of the
application on the device. The parameters are stored in the WMAppManifest.xml file. Even if
you try to change the XML file manually, your changes will be overwritten each time you
change and save your project settings via this dialog.

Task 2 – Building and Testing the Application in the Windows Phone Emulator
At the moment, the application does not do much, but it is ready for its first test run. In this task, you
build the application, deploy it to the Windows Phone Emulator, and then execute it to understand the
typical development cycle.
1. In the Debug menu, point to Windows and select Output to open the Output window.

Page | 15
Hello Windows Phone Hands-on Lab

2. Select Build Solution in the Debug menu or press the SHIFT + F6 key combination to compile
the projects in the solution.

Visual Studio 2010: Select Build Solution in the Build menu or press CTRL + SHIFT + B to
compile the projects in the solution.

3. Observe the Output window and review any trace messages generated during the build
process, including the final message with its outcome.

Figure 8
Building the application in Visual Studio

4. You should not observe any errors at this stage but, if the project were to contain compilation
errors, these would appear in the Output window. To deal with these kinds of errors, you can
take advantage of the Error List window. This window displays errors, warnings, and messages
produced by the compiler in a list that you can sort and filter based on the severity of the error.
Moreover, you can double-click an item in the list to automatically open the relevant source
code file and navigate to the source of the error. To open the Error List window, in the View
menu, point to Other Windows and select Error List.

Visual Studio 2010: To open the Error List window, in the View menu select Error List.

Page | 16
Hello Windows Phone Hands-on Lab

Figure 9
Error List window shows errors during the build process

5. Verify that the target of the deployment is the Windows Phone Emulator. To do this, ensure
that Windows Phone 7 Emulator is selected in the Select Target drop down next to the Start
Debugging button on the toolbar.

Figure 10
Choosing the target device to deploy the application

Note: When you deploy your application from Visual Studio, you have the option to deploy it
to a real device or to the Windows Phone Emulator.

6. 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 application image.

Page | 17
Hello Windows Phone Hands-on Lab

Figure 11
Deploying an application image to the Windows Phone Emulator

7. Once it is ready, the emulator shows the Start page and shortly thereafter, your application
appears in the emulator window.

Page | 18
Hello Windows Phone Hands-on Lab

Figure 12
Running the application in the Windows Phone Emulator

Page | 19
Hello Windows Phone Hands-on Lab

8. Until you create the user interface and program the application logic, there is very little that you
can do with the application at this stage. 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

Tip: 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.

Task 3 – Designing the User Interface


In this task, you create the UI elements for the HelloPhone application. The application is very simple.
When completed, the application UI will contain a caption, a textbox, and a button. To use the
application, you enter some text into the textbox and then, when you click the button, the application
displays a banner with the text that you typed. It will look something like the following figure.

Page | 20
Hello Windows Phone Hands-on Lab

Figure 14
The application’s user interface

1. In Solution Explorer, double-click MainPage.xaml to open this file in the designer.

Note: The designer provides two separate views to edit XAML files, Design and XAML view. In
Design mode, you have an interactive canvas where you drag and drop controls from the
toolbox, as well as select, resize, move, and set properties for existing controls on the designer
surface. In XAML mode, you have a markup editor that lets you edit the XAML in the page.
Tabs on the designer window let you select either mode. You also have a split mode, with the
editor window showing both views simultaneously. In split mode, you can use the
Expand Pane / Collapse Pane button to maximize the viewing area of the current mode.

Page | 21
Hello Windows Phone Hands-on Lab

2. While the IDE allows you to manipulate objects graphically, in this task, you will focus on
manually editing the XAML. Once completed, you will return to the Design view to review your
work. To set the editor mode to XAML view and maximize the viewing area, double-click the
XAML tab on the right edge of the designer window. If you have trouble identifying the correct
tab, position the mouse cursor over each tab to display a tooltip that identifies it.

Note: If you configured the designer to show a horizontal split view, the tabs are located on
the bottom edge of the window.

Figure 15
XAML designer showing the XAML views

3. In the XAML markup generated by the default Windows Phone application template, locate the
Grid container element named LayoutRoot. Its purpose is to arrange the elements on the page.
Inside its RowDefinition property, insert an additional row between the two existing rows and
set the value of its Height property to Auto. This row will soon include a textbox and a button.
XAML
...
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
Page | 22
Hello Windows Phone Hands-on Lab

<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
...

</Grid>
</phone:PhoneApplicationPage>

Note: A Grid is a layout element that acts as a container for other controls. Its main purpose is
to position and arrange its child controls. Several layout controls exist to provide alternative
layout behaviors:
Canvas: Defines an area within which you can explicitly position child elements by coordinates
relative to the Canvas area.
Grid: Defines a flexible grid area consisting of columns and rows.
StackPanel: Arranges child elements into a single line that can be oriented horizontally or
vertically.
For more information, see Silverlight Layout System.

4. Notice that the root Grid element contains other nested elements with each one assigned to a
different row of the outer grid by defining a Grid.Row property. Locate the Grid element named
TitlePanel. Set the Text property of the first TextBlock element inside the inner Grid to the
string “Windows Phone 7”. Similarly, set the Text property of the second TextBlock element to
the string “Hello Phone”.

Page | 23
Hello Windows Phone Hands-on Lab

Figure 16
Setting a caption for the application

Note: To assign child elements to a given row in the container grid, each one of the child
elements must specify a value for the Grid.Row property, which is considered to be an
attached property. Attached properties allow different child elements to specify unique values
for a property defined in a parent element; in this case, the Row property belongs to the Grid
element.

5. Now, locate the Grid element named ContentPanel, which should currently be empty, and paste
the following (blue-highlighted) XAML markup inside this element.
XAML
...
<Grid x:Name="LayoutRoot" Background="Transparent">
...
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.ColumnDefinitions>

Page | 24
Hello Windows Phone Hands-on Lab

<ColumnDefinition Width="*" />


<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Name="MessageTextBox" FontSize="{StaticResource
PhoneFontSizeExtraLarge}" Margin="20,20,10,20"/>
<Button Grid.Column="1" Name="ClickMeButton" Content="Click Me"
HorizontalAlignment="Right" Padding="4" Margin="10,20,20,20" />
</Grid>

</Grid>
...

Note: A Grid arranges its child controls on the page based on the width of each column as
defined in its ColumnDefinitions collection. Note that the width of the first column is specified
as *, which ensures that it stretches to fill the unused space in the row after all other columns
have been allocated, and that the width of the second column is set to Auto in order to size
the column to its content.

6. To complete the design of the page, add a third row to contain the banner with the message
entered by the user. To create this row, insert the following (blue-highlighted) XAML markup
immediately before the end tag of the outer grid.
XAML
...
<Grid x:Name="LayoutRoot" Background="Transparent">
...

<Grid Grid.Row="2">
<TextBlock Name="BannerTextBlock" Style="{StaticResource
PhoneTextExtraLargeStyle}"
Foreground="#FFFF9A00" HorizontalAlignment="Stretch"
TextWrapping="Wrap" TextAlignment="Center" FontWeight="Bold" />
</Grid>
</Grid>
...

7. Click the Design tab located on the right edge of the window to switch to design mode. Examine
the layout of the controls on the page, which should match the figure below.

Page | 25
Hello Windows Phone Hands-on Lab

Note: If you configured the designer to show a horizontal split view, the tabs are located on
the bottom edge of the window.

Figure 17
Viewing the page in Design mode

Task 4 – Handling Events from the User Interface


In this task, you define the event handlers that respond to actions from the user interface, namely the
button click event. You define event handlers using code in the code-behind file of the page.
1. Ensure that the mode of the designer is set to Design. To do this, double-click the Design tab on
the right edge of the designer window. If you have trouble identifying the correct tab, position
the mouse cursor over each tab to display a tooltip that identifies it.
2. Click the button labeled “Click Me” on the designer surface to select it and then press F4 to
open its Properties window.

Page | 26
Hello Windows Phone Hands-on Lab

3. In the Properties panel, click the Events tab to display a window with a list of available events.
Locate the Click event in this list and then type ClickMeButton_Click in the text box located next
to this event. Press ENTER to generate an event handler with this name and open the code-
behind file to display the method stub generated by Visual Studio.

Figure 18
Creating an event handler for the button

Figure 19
XAML view showing the new handler bound to the Click event

Page | 27
Hello Windows Phone Hands-on Lab

Note: There is an alternative mechanism to create the event handler. In Visual Studio, you can
double-click a control in the designer to create a handler for its default event, which happens
to be the Click event for button controls.

4. The method implementation (which is an empty method right now) is in the MainPage.xaml.cs
file. Insert the following code inside the body of the ClickMeButton_Click method.
C#
private void ClickMeButton_Click(object sender, RoutedEventArgs e)
{
BannerTextBlock.Text = MessageTextBox.Text;
MessageTextBox.Text = String.Empty;
}

Note: The code reads the text entered by the user from the text box and then sets the banner
with this text.

Task 5 – Verification
In this task, you build, deploy, and run the application in the Windows Phone Emulator to test that it
works as expected. In addition, you set a breakpoint, use the debugger to step through the source code,
and examine the value of variables for a brief glimpse at how you can use Visual Studio to debug
applications running in the emulator.
1. If necessary, re-open the code-behind file for MainPage.xaml. To do this, right-click this file in
Solution Explorer and then select View Code.
2. Now, define a breakpoint to stop execution at the event handler for the “Click Me” button. To
set the breakpoint, locate the first line of the ClickMeButton_Click method in the source file
and then click the area in the gray margin located on the left side of the editor window, next to
this line. A red circle ( ) indicates the position of the inserted breakpoint. Alternatively, click
the line in the editor window to select it and then press F9.

Page | 28
Hello Windows Phone Hands-on Lab

Figure 20
Setting breakpoints in Visual Studio

Note: To toggle a breakpoint on or off, click the in the margin area or click the line that
contains the breakpoint and press F9.

3. Press F5 to build and deploy the application to the Windows Phone Emulator and start the
debugging session. Wait for the application to launch and display its main page.

Note: If you kept the emulator running after you used it earlier in the lab, launching the
application should only take a couple of seconds; if you closed the emulator, it might take
longer.

4. In the emulator window, click on the text box to give it focus. This will cause the Software Input
Panel (SIP) to open automatically. You can type a message using the panel or press the
PAUSE/BREAK key to use your desktop keyboard instead. After entering some text into the text
box, click the button next to it.

Page | 29
Hello Windows Phone Hands-on Lab

Figure 21
Typing on the emulator

Note: The need to press the PAUSE/BREAK key is a known issue and will be fixed in future
releases.

5. Back in Visual Studio, notice that execution stops at the breakpoint that you set previously and
that the next statement to execute appears highlighted in yellow.

Page | 30
Hello Windows Phone Hands-on Lab

Figure 22
Stepping through code in the debugger

6. Examine the current contents of the text box in the debugger. To do this, in the source window,
place the mouse cursor over the MessageTextBox.Text property. A tooltip window—commonly
known as a datatip—pops up to display the current value of the property, which should match
the text you entered in the emulator window. Make sure that the cursor is over the Text part;
otherwise, the datatip displays information about the MessageTextBox object instead.

Figure 23
Examining the value of variables in the debugger

Note: You can examine the state of any object currently in scope by placing the mouse pointer
over the corresponding variable.
Page | 31
Hello Windows Phone Hands-on Lab

7. Press F10 to single-step over the current statement and set the text of the banner to the
contents of the text box. Display the datatip for the BannerTextBlock.Text property to confirm
that its value now matches that of the text box.

Note: When you use F10, you instruct the debugger to step over the current statement. You
can also use F11 to step into the current statement. In that case, if that statement involves a
method call, the debugger steps into the target method to allow you debug it.

8. Press F10 once again to execute the next statement and clear the contents of the text box. Once
again, display the datatip for the MessageTextBox.Text property, which is still in scope, and
confirm that it is now empty.
9. Finally, press F5 to resume execution of the application. Switch back to the Windows Phone
Emulator. If necessary, dismiss the lock screen in the emulator window.

Tip: Depending on configuration settings, the Windows Phone Emulator could show a lock
screen whenever the application remains idle for a short period. To restore the application,
use a “flick” gesture—where you click the emulator window surface followed by a quick
upward movement with the mouse button still down—to slide the lock screen up. Observe
that the banner in the emulator window now shows the text that you entered.

Page | 32
Hello Windows Phone Hands-on Lab

Figure 24
HelloPhone application running in the Windows Phone Emulator

10. Click the Back button in the emulator to navigate to the previous page. Notice that when you do
this, the debugging session ends and the emulator displays its start menu because you are
navigating away from the first (and only) page of the application and there are no previous
applications currently active.

Tip: To resume debugging after the current session ends, press F5 to launch the application
again and re-attach the debugger. Note, however, that this action starts the application again
and the previous state will no longer be available.
Closing the emulator stops the application and detaches the debugger. When you do this, the
Visual Studio debugger detaches and display a message indicating that it has lost connection to
the device
Page | 33
Hello Windows Phone Hands-on Lab

Figure 25
A debugging session ends when you navigate away from the application

Exercise 2: Using Expression Blend to


Design the UX of your Windows Phone
Application
In the same way that you use Expression Blend to design Rich Internet Applications for the desktop
browser, you can also design creative and unique Silverlight-based applications on a Windows Phone.
Expression Blend for Windows Phone allows you to create XAML-based interfaces for Windows Phone
applications, whose behaviors can then be implemented by developers in Visual Studio.
Microsoft Expression Blend for Window Phone is included as part of the installation of Windows Phone
Developer Tools. Alternatively, you can download Microsoft Expression Blend 4 and install the Add-in for
Windows Phone.
Task 1 – Creating a Custom Button in Expression Blend
In general, Silverlight controls separate their logic from their visual appearance using templates. A
ControlTemplate specifies the visual structure and visual behavior of a control. You can customize the
appearance of most controls by modifying their default ControlTemplate settings. This allows you to
change the appearance of the control without changing its functionality. For example, you can make the
buttons in your application round rather than the default square shape, but the button will still raise the
Click event.

Page | 34
Hello Windows Phone Hands-on Lab

In this task, you open the Visual Studio project that you created in the previous exercise in Expression
Blend and replace the ControlTemplate of the button to alter its look and feel. Because you create a
ControlTemplate in XAML, you can change a control's appearance without writing any code.

Figure 26
Changing the look and feel of controls

1. If not already open, launch Microsoft Visual Studio 2010 Express for Windows Phone from Start
| All Programs | Microsoft Visual Studio 2010 Express for Windows Phone.

Visual Studio 2010: Open Visual Studio 2010 from Start | All Programs | Microsoft Visual
Studio 2010.

2. If you completed the steps in the previous exercise, you may continue with the solution that
you created for that exercise; otherwise, open Begin.sln from HelloPhone\Ex2-
WP7AppUXDesignWithBlend\Begin in the Source folder of the lab.
3. Now, open the current solution in Expression Blend. To do this from Visual Studio, right-click
MainPage.xaml in Solution Explorer, and then select Open in Expression Blend.
If a warning from a security risk is displayed, click Yes to dismiss it.

Page | 35
Hello Windows Phone Hands-on Lab

Figure 27
Opening the solution with Expression Blend

4. In Expression Blend, make certain that the MainPage.xaml is open in the designer window—if
necessary, double-click the file in the Projects panel to open it—and that the current workspace
is set to Design. To view the current workspace, select Workspaces in the Window menu and
ensure that the Design option is checked.

Figure 28
Selecting the current workspace in Expression Blend

Note: The workspace in Expression Blend consists of all the visual interface elements. These
include the artboard, panels, tools panel, workspace configurations, authoring views, and
menus.

Page | 36
Hello Windows Phone Hands-on Lab

5. In the designer window, right-click the “Click Me” button, point to Edit Template and select
Create Empty.
6. In the Create ControlTemplate Resource dialog, set the Name to FancyButton, keep the current
value of "This document" in the Define in option, and click OK.

Figure 29
Creating an empty control template for the button

Note: Resources provide a simple way to reuse commonly defined objects and values. You can
create definitions for common items including control templates, styles, brushes, colors, and
animations and store them in resource dictionaries. A resource dictionary is a keyed dictionary
of objects that you can use both in XAML and in code. You can create resource dictionaries at
different scopes in your application structure, allowing you to define resources at the page
level or as application resources.
The dialog shown above gives you the option to define the control template at the global
Application scope, in which case it is stored in App.xaml and you can reuse the template in
other pages of the application, or store it in This document so that you can use it only within
the same page.

7. If the Objects and Timeline panel is not visible, select Window and then Objects and Timeline
to show this panel. If necessary, you can reset the workspace to its default state by selecting
Window | Reset Current Workspace.

Page | 37
Hello Windows Phone Hands-on Lab

Note: When you create a new template, Expression Blend enters a mode in which you can
view and edit the new template. In the Objects and Timeline panel, the word Template at the
root of the new element tree indicates the current scope in which you are editing.

8. Change the current root layout container of the template. In the Objects and Timeline panel,
right-click the child Grid element inside Template, point to Change Layout Type, and select
Border.

Figure 30
Changing the root layout container of the template

Note: When you create a ControlTemplate, you combine FrameworkElement objects to build
a single control. A ControlTemplate must have only one FrameworkElement as its root

Page | 38
Hello Windows Phone Hands-on Lab

element. The root element usually contains other FrameworkElement objects. The
combination of objects is makes up the control's visual structure.

9. With the Border element still selected in the Objects and Timeline panel, switch to the
Properties panel and under Appearance, set the value of the BorderThickness property to 2 for
each of the sides and then set the value of the CornerRadius property to 15.

Figure 31
Configuring the appearance of the border element

10. Now, in the Brushes section, select the Background property and pick the Gradient brush
option. Then, click the left gradient stop to select it and set its value to a light gray color, for
example #FFADADAD. Next, select the right gradient stop and set its value to a dark gray color,
for example #FF0A0A0A.

Page | 39
Hello Windows Phone Hands-on Lab

Figure 32
Configuring a gradient brush for the button background

11. After that, in the Brushes section, select the BorderBrush property, choose a Solid color brush
and choose a light gray color, for example #FFC0C0C0.

Page | 40
Hello Windows Phone Hands-on Lab

Figure 33
Configuring a solid brush for the button border

12. Once you have created a background for your button, the next step is adding a caption. First,
ensure that the Border element remains selected in the Objects and Timeline panel.
13. Next, switch to the Assets panel, select the Controls category, and scroll down the list displayed
to the right of the category to locate the TextBlock control. Then, double-click the item in the
list to insert an instance of this control nested inside the Border element of the template.

Page | 41
Hello Windows Phone Hands-on Lab

Figure 34
Inserting a TextBlock control from the toolbox

Figure 35
Objects and Timeline panel showing the new TextBlock nested inside the Border element

14. Now, in the Tools panel, pick the Selection tool or press V to restore selection mode.

Page | 42
Hello Windows Phone Hands-on Lab

Note: After inserting the TextBlock, the designer remains in insertion mode and you can
continue adding other TextBlock elements until you exit this mode.

15. In the Objects and Timeline panel, select the newly added TextBlock element. Then, in the
Properties panel, expand the Brushes category and set the Foreground brush to a light color,
for example #FFFFFFFF.

Figure 36
Setting the foreground color of the button

16. Next, expand the Layout category and set the value of the HorizontalAlignment and
VerticalAlignment properties to Center. Then, set the value of the Margin property to 10 for the
left and right sides, and to 4 for the top and bottom sides.

Page | 43
Hello Windows Phone Hands-on Lab

Figure 37
Configuring the margin and alignment properties of the caption

17. Link the Text property of the TextBox control in the template to the Content property of the
button templated control. To do this:
◦ Expand the Common Properties category
◦ Click Advanced property options—indicated by a square icon next to the value of the
property
◦ Select Template Binding to display a list of properties in the templated control that can
be bound to this property
◦ Choose the Content property from this list
Notice that the value of the Text property changes to “Click Me”—the value currently
set for the Content property of the button—and that the property is now shown with a
yellow outline to indicate that it is template-bound.

Page | 44
Hello Windows Phone Hands-on Lab

Figure 38
Binding the Text property of the template

Note: Template binding links the value of a property in a control template to be the value of
some other exposed property on the templated control allowing you to design a customized
control, but still enable some changes when you include the control in your application.

18. Press CTRL + S to save the updated file.


You are now ready to test the new custom button. Expression Blend for Windows Phone allows
you to run your Windows Phone applications either on an actual phone device, or on an
emulator. Notice that If you open the Device panel (from Window menu), you can choose where
to preview your application. By default Expression Blend will use the Windows Phone Emulator
to deploy and run the applications.

Page | 45
Hello Windows Phone Hands-on Lab

Figure 39
Binding the Text property of the template

19. Now press F5 to build and run the application. Enter some text and then click the button.

Figure 40
Launching the application from Expression Blend
Page | 46
Hello Windows Phone Hands-on Lab

Notice that even though the click triggers the expected behavior, there is no visual cue to
indicate when the button has focus or when it is pressed. In the following task, you will update
the template to change the appearance of the button based on its state.

Task 2 – Adding Visual States to the Custom Control


In this task, you will update the control template to add different visual states that allow the button to
show an outline when it is focused, and to shift its position on the page to indicate when it is pressed.
1. In the Objects and Timeline panel, select the Border control.
2. Now, switch to the States panel and examine the visual states available for the button control.

Figure 41
States panel showing the Base state selected

Note: The States panel shows all the available visual states of the control. The Base state
defines elements that are common to every state. In this state, you customize the template to
define the basic appearance of the control. Then, for each of the other states, you change the
template in such a way that it provides a visual cue of the corresponding state, for example, in
the Focused state, by displaying a border around the control.

Page | 47
Hello Windows Phone Hands-on Lab

3. Under the FocusStates category, select the Unfocused state to turn on recording for the state
triggered when the button does not have the focus.
Any changes to the template while in this mode apply only to that particular state.

Figure 42
State recording in Expression Blend

Note: Several changes occur when you select a state other than normal. First, a red circle next
to the selected state’s label indicates that it is currently active. Next, a red outline appears
around the design area. Finally, a caption in the upper left corner of the design area indicates
that state recording is on. In this mode, any changes to the elements of the template are
recorded and stored in the XAML document. At runtime, these changes are applied to the base
template when that state becomes active.

4. To hide the border around the button when it loses focus:

◦ Select Border in the Objects and Timeline panel


◦ In the Properties panel, expand the Brushes category and select the BorderBrush
property

◦ Click the Show advanced properties icon and set the Opacity property of the brush
to 0.
Page | 48
Hello Windows Phone Hands-on Lab

Figure 43
Making the border transparent for the Unfocused state

5. Go back to the States panel and select the Pressed state in the CommonStates category to turn
on recording for the state triggered when the mouse is clicked.
6. In the Properties panel, expand the Transform category and select the Translate transform. Set
the X and Y values to 2.
This change produces a slight shift in the position of the button whenever it is clicked, to suggest
that it is pressed down.

Page | 49
Hello Windows Phone Hands-on Lab

Figure 44
Shifting the position of the button during the Pressed state

7. Finally, in the States panel, select the Base template to turn off recording mode.
8. Press CTRL + S to save the updated file.
9. Now that you have completed adding visual states to the custom control, you are ready to test
the updated button:
◦ Press F5 to build and run the application
◦ Enter some text and then press the Tab key to change the input focus to the button

◦ Notice that, when the button has focus, a border appears around the button indicating
that it is active
◦ Now, press the space bar or click the button and notice how its position shifts to
indicate that it depressed

Page | 50
Hello Windows Phone Hands-on Lab

Task 3 – Creating an Animation for the Banner Text


Animations are based on key frames that define the start and end points of a smooth visual transition.
To create an animation in Expression Blend, you create a storyboard, and in the storyboard, you set key
frames on a timeline to mark property changes. For example, you could set a key frame at the 0-second
mark to record the position of a rectangle on the left side of the artboard, and then set a key frame at
the 1-second mark to record the position of the same rectangle on the right side of the artboard. The
resulting animation would be based on the transformation that occurs on the X and Y properties of the
rectangle over one second. When you run an animation storyboard, Expression Blend interpolates the
property changes over the designated time period and displays the results in your application. You can
animate any property that belongs to an object on the artboard in this manner, even non-visual
properties.
In this task, you will create a storyboard in Expression Blend to animate the text in the banner whenever
the button is pressed.
1. Switch the active workspace to the animation workspace. In the Window menu, point to
Workspaces and select Animation.
Notice that this rearranges the windows in order to maximize the space available to edit the
timeline.

Note: To restore a workspace to its default state, select Window | Reset Current Workspace.

2. If necessary, exit the editing scope of the button control template. To do this, click the Scope Up

button next to the FancyButton (Button Template) element in the Objects and Timeline
panel to display the element tree of the page.

Note: When you edit a control template, the Objects and Timeline panel only shows the
element tree for that template. To edit other elements on the page, you need to exit the
current scope.

3. Now, in the Objects and Timeline panel, click New to create a storyboard. This is the button
labeled with a + sign and located in the upper right corner of the panel.

Page | 51
Hello Windows Phone Hands-on Lab

Figure 45
Objects and timeline pane in Animation mode

4. In the Create Storyboard Resource dialog, set the Name to AnimateBanner and click OK.

Figure 46
Creating a new storyboard to animate the banner text

5. To create the key frames in the animation, first, click the BannerTextBlock element in the
element tree of the Objects and Timeline panel to select it. If necessary, expand its grid parent
element to display it.
6. Then, click and drag the current position of the timeline playhead to an offset of 1 second.

Page | 52
Hello Windows Phone Hands-on Lab

Figure 47
Changing the time offset of the timeline playhead

Note: The playhead is the yellow marker located at the top of the timeline. Any changes to the
elements in the page are recorded as key frames at the location of the timeline playhead.

7. Next, switch to the Properties panel, expand the Transform category, and select the Scale
transform. Set the value of the X property to -1. This transform mirrors the element along its
horizontal axis.

Page | 53
Hello Windows Phone Hands-on Lab

Figure 48
Applying a scale transformation to mirror the text

8. Switch back to the timeline panel.


Notice that it contains a new key frame—indicated by a gray circle—at the chosen time offset
that is the result of changing elements in the tree while timeline recording is active.

Page | 54
Hello Windows Phone Hands-on Lab

Figure 49
Creating a new key frame in the animation storyboard

9. Now, change the timeline playhead to an offset of 2 seconds.


10. Once again, switch to the Properties panel, expand the Transform category, and select the
Scale transform. Change the value of the X property back to 1 to restore the element to its
original state.
Notice that a second key frame appeared in the storyboard timeline because of this change.

Figure 50
Objects and Timeline panel showing the inserted key frames

Page | 55
Hello Windows Phone Hands-on Lab

11. To test animation in the designer, you need to add some text to the banner. First, click the red
circle to the left of the AnimateBanner storyboard name in the upper left corner of the panel to
turn off recording temporarily—you do not want the added text to become part of the
animation.

Figure 51
Turning off recording mode

Note: When you turn off recording, any changes to elements in the page are not included in
the animation.

12. Now, right-click the BannerTextBlock element on the designer surface and select Edit Text.
Enter a suitable text for the banner and press ENTER.
13. To test the animation, press the Play button above the timeline.
Notice how the text in the banner rotates horizontally about its middle axis and how the
movement is uniform throughout the animation cycle. In the following steps, you will apply an
easing function to change the interpolation between key frames and produce a more natural
animation.

Page | 56
Hello Windows Phone Hands-on Lab

Figure 52
Playing the animation in the designer

14. Select the first key frame by clicking inside the gray circle icon in the timeline.
Notice that when you select a frame, the designer view updates to show the state of the UI
elements as they appear in that frame, in this case, the banner text appears mirrored.
Now, in the Properties panel, under the Easing category, ensure that EasingFunction is selected,
expand the drop down list to display a list of available functions, and then choose the Cubic Out
function.
This particular easing function causes the transition to reduce its rate as it approaches the key
frame.

Page | 57
Hello Windows Phone Hands-on Lab

Figure 53
Applying an easing function to interpolate between key frames

Note: Key frame interpolation describes how property changes are animated in the span of
time between two key frames. You can modify key frame interpolation values by applying an
easing function to the transition to obtain a more realistic animation.

15. Repeat the procedure in the previous step to configure the easing function for the second key
frame. This time choose the Cubic InOut function to make the transition start at a slow rate,
gradually accelerate, and finally reduce its speed as it approaches the ending frame.

Page | 58
Hello Windows Phone Hands-on Lab

Figure 54
Choosing the CubicInOut easing function

16. To test the effect of the easing functions on the animation, press Play above the timeline.
Notice how the banner starts its rotation at a high rate, then slows down as the text appears
mirrored, it then picks up speed again and finally slows down once again to return to its original
position.
17. So far, you have created an animation storyboard for the banner text, but it simply exists as an
unused resource in the project. To play the animation, you need to trigger the storyboard in
response to an event, in this case, whenever the Click Me button is pressed. To open the Click
event handler for this button:
◦ Switch the active workspace back to the design workspace. In the Window menu, point
to Workspaces and select Design.

◦ In the Projects Window, click the arrow ( ) next to MainPage.xaml, to display its code-
behind file.
◦ Double-click MainPage.xaml.cs to open the code-behind view.

18. To update the event handler to play the animation, insert the following code snippet into the
highlighted space immediately before the ending brace.
C#

Page | 59
Hello Windows Phone Hands-on Lab

private void ClickMeButton_Click(object sender, RoutedEventArgs e)


{
BannerTextBlock.Text = MessageTextBox.Text;
MessageTextBox.Text = String.Empty;
this.AnimateBanner.Begin();
}

Task 4 – Verification
In this task, you run the application in the Windows Phone Emulator from Expression Blend to see the
result of your changes to the user interface.
1. Press F5 to build and deploy the application to the Windows Phone Emulator. Wait for the
application to launch and display its main page.
2. Enter some text into the text box.
3. Press the Tab key once and observe the border shown around the button when it receives
focus.
4. Click the button to set the text of the banner and notice how it shifts its position to indicate that
it is pressed.
Watch the animation of the banner text play when you click the button.

Page | 60
Hello Windows Phone Hands-on Lab

Figure 55
Running the updated application in the Windows Phone Emulator

5. When you have completed your testing, click the Close icon in the upper right corner of the
emulator window to shut it down and end the debugging session.

Note: Shutting down the emulator is recommended only if you do not intend to run the
application again; otherwise, leave the emulator open and redeploy and debug the application
whenever you need to test an update.

Summary
Page | 61
Hello Windows Phone Hands-on Lab

This lab introduces how to develop applications for the Windows Phone platform using Silverlight. By
completing this hands-on lab, you became familiar with the tools required to create and test a Windows
Phone application.
In this lab, you created a new Silverlight for Windows Phone application using Microsoft Visual Studio
2010 Express for Windows Phone, and then used this free tool to create the application logic and the
layout of the user interface. You learned how to deploy the application to the Windows Phone emulator
and how to use the debugger to set breakpoints, single-step through the program and examine the
value of program variables. Finally, you saw how use Expression Blend for Windows Phone to style
controls in the user interface and create animation effects.

Page | 62

You might also like