Developing a Silverlight Application for Windows Phone 7
Developing a Silverlight Application for Windows Phone 7
By Colin Melia
8,316 Downloads · Refcard 127 of 185 (see them all)
Download
FREE PDF
The Essential WP7 Silverlight Cheat Sheet
Developing a Silverlight Application forWindows® Phone 7
PLATFORM & TOOLS
Windows® Phone 7 is a new platform bringing together developers from the .NET, Silverlight, and XNA eco-systems. This document combines reference information and tips for developing and publishing a Silverlight application for the platform using Visual Studio.
Hardware Specification
All initially launched Windows Phone 7 devices come with: the same operating system; the same minimum set of builtin applications and platform capabilities; and the ability to run Silverlight and XNA applications. Additionally, all devices come with the following hardware capabilities:
- 480x800 display
- DirectX 9 hardware acceleration
- Capacitive 4-point multi-touch
- Back, Start & Search hardware buttons (as well as a power, camera and volume button)
- A-GPS, accelerometer, compass*, light*, proximity*
- 5 MP+ digital camera with flash
- 256MB+ RAM
- 8GB+ flash storage
* not accesible from .NET API in initial release
Hardware manufacturers may differentiate their devices by items such as: having higher RAM, flash storage or camera mega-pixels; having different screen sizes (but same resolution); adding a slide-out keyboard (horizontal or vertical); adding a single additional theme accent color; bundling additional built-in applications—but not removing/ replacing built-in applications/UI.

Developer Tools
The developer tools for Windows Phone 7 are available for free. Go to http://go.microsoft.com/fwlink/?LinkID=189554 for the RTW (‘Released to the Web’) tools or go to http://create.msdn.com to find the latest set.
The developer tools include the following items in one package:
- Visual Studio 2010 Express for Windows Phone*
- XNA Game Studio 4.0*
- Microsoft Expression Blend for Windows Phone*
- Windows Phone Emulator Resources
- Silverlight 4 Tools For Visual Studio
*Items 1 & 2 will install as standalone applications if Visual Studio 2010 Professional or higher is not installed, otherwise they will install additional project templates in Visual Studio. The same goes for item 3 with regard to Expression Blend 4.
To install the RTW version of the tools, one of the following is required:
- Windows® Vista® (x86 and x64) with Service Pack 2–all editions except Starter Edition
- Windows® 7 (x86 and x64)–all editions except Starter Edition
Be sure to check out the release notes for full requirements. http://go.microsoft.com/fwlink/?LinkID=190374

Silverlight Application Platform
The Windows Phone 7 platform can run applications based on Silverlight and XNA.
Silverlight is often the preferred choice for applications built with controls and events, similar to WinForms or WebForms. XNA is typically used for higher performance UI hardware rendering in 2D and 3D.

Silverlight applications run directly on the Windows Phone platform in a mode similar to the out-of-browser capability of Silverlight 3+ on the desktop. They do not run in a browser. In fact, Silverlight content on Web pages will not appear in the phone’s Web browser, but there is a WebBrowser control to host HTML content (from the Web, injected, or from local storage) inside a Silverlight application.
The RTW Silverlight platform is based largely on Silverlight 3.
A notable Silverlight 3 feature that is missing is TCP socket network access. A notable Silverlight 4 feature that is included is multi-touch manipulation events and offline DRM.
For general information on Silverlight support on the phone, see the MSDN library section: http://msdn.microsoft.com/en-us/library/ff426934(v=VS.95).aspx

The phone platform includes a set of classes specific to Windows Phone: http://msdn.microsoft.com/en-us/library/ff626516(v=VS.92).aspx.
SILVERLIGHT PROJECT CREATION
Project Templates
Start building a Silverlight application for Windows Phone by using the File -> New Project feature in Visual Studio. The RTW tools include support for projects based on the C# language. Support for VB.NET will be officially introduced later on.
| Project Template Type | Likely Used When… |
| Windows Phone Application | Starting with a basic one-page/screen application. |
| Windows Phone Databound Application | Starting with a one-page/screen list-based application and including MVVM (Model-View-ViewModel) design. |
| Windows Phone Class Library | Building a component or control to reuse in other projects. |
| Windows Phone Panorama Application* | Building an application that is based on an MVM design and that starts with a rich and wide content-based starting screen like the People, Music + Videos, Pictures, Office, Xbox Live, and Marketplace.” |
| Windows Phone Pivot Application* | Building an application that is based on an MVM design and that starts with a screen showing set of views (or pivots) over data like the Calendar & email application on the phone. |
* These project templates use the Panaroma and Pivot controls on a single page and are often used to create ‘Hub’ applications; these controls can also be added to any page in an application.

Design Surface + XAML
After choosing to create a new project based on the Windows Phone Application template, an interface is shown that includes windows for the Toolbox, Solution Explorer, and Properties, along with the editor window for the initial (and perhaps only) application page named MainPage.xaml.
The editor window is split between a preview design surface and Extensible Application Markup Language (XAML) editor. Drag and drop controls from the toolbox to either the design surface or the XAML text. By selecting items on the design surface or XAML text (which synchronize their selections), properties can be changed in the Properties window.
XAML is based on XML and is parsed at runtime to instantiate objects, creating a way to perform declarative programming.
The XAML used in Silverlight represents a tree of objects largely used to form the tree of visual controls in the running application. It can also be used to instantiate reusable resource objects and class instance objects.
Key elements of the XAML syntax are:
- Default namespace: XML feature that defines the set of elements (and their attributes) that can be used in the document. At runtime, these elements are matched to classes in a .NET assembly.
- Element: using an XML element means an object with a type named the same as the element will be created at runtime.
- Attribute: at runtime, the value of an attribute will be set as the value of a property on the object created for the corresponding element. The XAML parser is also able to convert text to non-text types including a numerical type, an enumerated type, multiple initial values on a type (e.g. the different sides of a Margin), or a whole object initialized by the attribute values (e.g. a SolidColorBrush with a specific color).
- Nesting: putting one element inside another means the created objects form a tree whereby the nested object is assigned to a default property (e.g., a single Child or Content property of the containing object), or it becomes one of several objects added to a default collection property (e.g., a Children collection property).
- Property Element: when a property of an object is too complex to declare or parse from an XML text attribute, the Property Element syntax is used to declare the object fully
- Attached Properties: this allows a containing object to declare properties against each child object without the class of each child object needing to have members (e.g. a set of Button objects could be placed in a radial layout control which visually lays out the buttons in a circle; that layout control needs each Button to have an angle property value).
- Extensibility: to introduce elements that become types from other .NET assemblies (e.g., other controls or classes), use this kind of XML namespace declaration.
- x:Name: similar to ASP.NET ID attribute; to access the instantiated objects from procedure code, give them a name.
- Evaluated: The {} syntax is used to evaluate value at runtime, e.g., accessing resources or binding to data.
You can (and may need to in some cases) use procedural code in the MainPage.xaml.cs file to build UI and populate it with data. However, XAML provides a more efficient way to declare visual interfaces rather than writing procedural code that can be substantially longer. Procedural code is still used for data models and accessing data. XAML is also compatible with the Expression Blend designer tool allowing for projects to be edited in both tools with tool UI appropriate to each user.

Controls
The following controls are provided on the phone:
| Category | Control Class |
| Do Action | Button, HyperlinkButton |
| Data Display | Map, ProgressBar, TextBlock, WebBrowser |
| Data Input | CheckBox, PasswordBox, RadioButton, Slider, TextBox |
| Media | MediaElement |
| Drawing | Ellipse, Rectangle |
| Layout | Border, Canvas, Grid, ListBox, ScrollViewer, StackPanel, Panorama, Pivot |
Many controls have a property named Content. Such controls (e.g., Border or even Button) act as visual/object container for rendering a single item of content which can be either:
- visual (derived from UIElement), e.g., another Control
- an object containing data (in which case the data is visually represented as text by calling ToString() or with other visual elements declared in a DataTemplate)

Layout
The desired UI layout is achieved by setting Margin and Padding on controls, setting their alignment in the space provided to them, and placing them in other controls (e.g., Grid, Canvas, or StackPanel) that arrange one or more controls.

Layout of controls on the design surface is not limited to the physical dimensions of the device. A control can extend passed the dimensions of the design surface if the user is able to reach that UI through some means of interaction. The Panorama and Pivot controls are ‘über-layout’ controls that do exactly this.
Emulator
The toolset includes a powerful emulator running the Windows Phone OS 7.0 compiled for Intel processors. It emulates a device’s processor, RAM, display, GPU, networking, media, keyboard, orientation changes, as well as application deployment and debugging. The PC mouse pointer is used to emulate a single screen touch. If the PC supports multi-touch, then this is passed through to the emulator.

The emulator starts automatically when a debug session is started in Visual Studio (if the Windows Phone 7 Emulator is selected).

The emulator does not emulate A-GPS, light, proximity, and accelerometer sensors. It also does not include all user Settings pages.


Debugging
- Visual Studio allows debugging targeting to the Emulator or a connected device for debugging.
- Regular debugging activities are available including using breakpoints, variable inspection, variable watch, call stack, and output window.
- The device must be ‘development unlocked’ (not the same as ‘network unlocked’); this is achieved by using the Windows Phone Developer Registration Tool (included with the tools) and having a developer account at http://create.msdn.com with a spare slot (out of 3 total for paying accounts; 1 for student accounts).
- The device must be on and not on the lock screen.
When using the emulator, leave it running between debug sessions to avoid the start-up time and to keep the storage emulation intact and be able to launch applications deployed/debugged since it was started.

APPLICATION NAVIGATION
Frame & Page
Silverlight applications on the phone operate within a logicial ‘last-on-first-off’ (LIFO) stack of running applications. Within an application, there is a logical LIFO stack of pages.
Other pages within an application (added with the ‘Add New Item’ menu item in Visual Studio) are launched by developed code, usually in response to user actions such as clicking a button.
private void button1_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri(“/page2.xaml?param=” + value,
UriKind.Relative));
}
This example shows passing a parameter to the next page. During page navigation, the current page’s OnNavigatedFrom() override is called and the destination page’s OnNavigatedTo() override is called.
protected override void OnNavigatedTo(System.Windows.Navigation.
NavigationEventArgs e)
{
var value = NavigationContext.QueryString[“param”];
}
In this case, the query string passed earlier is being extracted. The user launches instances of an application using the Search or Start screen ‘on top’, which sit logically higher on the sack.

Back Button
The phone’s Back button removes the current page and navigates to the previous one on the stack, calling its OnNavigatedTo() override. It is possible to cancel this default behavior. In the example, the modal dialog box is cancelled and prompts the user to save unsaved data.

protected override void OnBackKeyPress(System.ComponentModel.
CancelEventArgs e)
{
if (someallowedcondition)
e.Cancel = true;
base.OnBackKeyPress(e);
}
DATA HANDLING
Internet Data Access
There are three main methods provided for obtaining data from the Internet. All follow an asynchronous pattern.
| Method | Usage |
| Client Proxy | Use Add Service Reference to create a strongly-typed proxy class on a Web Service or WCF service supporting wsBasicBinding. |
| WebClient class | Use to get (or send) text data (including arbitrary XML) or a file. |
| HttpWebRequest & HttpWebResponse | Use for fine-grained control of sending an HTTP request and receiving the response. |
The typical pattern involves reacting to a user event (or timed event from System.Windows.Threading.DispatcherTimer) and setting up the data request by creating a class instance, setting up an event handler (or delegate), and initiating the asynchronous activity.

LINQ to XML
On the phone, LINQ allows set-based queries on in-memory objects and data transformation. This can include parsing text downloaded with WebClient and transforming it to objects. LINQ to XML (by adding the System.Xml.Linq reference) allows parsing and transforming of XML data.
public class MyPerson
{
public String Name { get; set; }
public int Age { get; set; }
}
Code to parse XML downloaded using WebClient, into the class.
// Do something with e.Result string
XDocument doc = XDocument.Load(new StringReader(e.Result));
var results = from p in doc.Element(“People”)
.Elements(“Person”)
select new MyPerson()
{
Name = p.Element(“Name”).Value,
Age = int.Parse(p.Attribute(“Age”).Value)
};
Data Binding
Data can be set on UI controls using procedural code, but this can get quite complex and is not designer-tool friendly. Setting (in code or XAML) the DataContext of any UI object (inherited from FrameworkElement) to a ‘data’ object (e.g., of type MyPerson) ‘binds’ that data object to the UI object and allows the UI object (or descendants) to display properties of the data object using a simple XAML syntax.
public MainPage()
{
InitializeComponent();
ContentPanel.DataContext = new MyPerson();
}
<Grid x:Name=”ContentPanel” Grid.Row=”1” Margin=”12,0,12,0”>
<TextBlock Text=”{Binding Name}”/>
<TextBlock Text=”{Binding Age}”/>
</Grid>
Setting the DataContext of descendant UI objects to any object properties of the data object allows a hierarchy of binding.

Isolated Storage
Isolated storage classes provide access to an area of storage on the device that is for the exclusive use of the calling application. This means applications cannot access data stored by other application (with only a few very special exceptions), and there is no file explorer for the end user.
Basic settings storage can be achieved like so:
// Store
IsolatedStorageSettings.ApplicationSettings[“mysetting”] = person;
// Retrieve - Use Try/Catch or check first with ApplicationSettings.
Contains()
MyPerson person = (MyPerson)IsolatedStorageSettings.ApplicationSettings[“m
ysetting”];
Alternatively, get a store object that allows file and directory operations. The CreateFile() and OpenFile() methods return back objects inherited from System.IO for use with Text, Binary, and XML Writers/Readers.
IsolatedStorageFile store = IsolatedStorageFile.
GetUserStoreForApplication();

PLATFORM INTEGRATION
Application Lifecycle
While the OS maintains a history of navigation between applications and pages, applications (as a rule) terminate when the application goes into the background. Some examples of this are when the user launches other applications including the Start screen, a launcher/choose task is launched (see “Launchers & Choosers”, or the screen locks. This provides the best user experience. Applications restart them at the last shown page when the user returns to the application using the Back button. The application developer must do the work to retain any UI or in-memory state by storing it either in isolated storage or with the ‘bag’ of data that the OS provides and retains in the stack history, known as the ‘tombstone’. App.xaml.cs includes the stub for four application lifecycle events.
- The Launching event fires every time the application launches. Initiate loading any settings or cached data from Isolated Storage (and check the Internet for any new data if appropriate).
- The Deactivated event fires when the application is ‘tombstoned’, with ~10 seconds to save data into the tombstone or Isolated Storage before the application terminates.
- The Activated event fires when the application is resumed via the Back button. Load back data from the tombstone or Isolated Storage (and check the Internet for any new data if appropriate).
- The Closing event fires when the application exits from the initial back via the Back button.
Tombstone data can be stored under the global PhoneApplicationService.Current.State dictionary (during Deactivate/Activates events) or in the current page’s State dictionary (during OnNavigatedFrom()/OnNavigatedTo()).
Note that the tombstone will be removed if the same application is launched again ‘on top’—the user is abandoning any ‘session’ data stored in the tombstone—or if the OS needs to free up resources. In either case, the last two events will never be called on the previously running instance.

Launchers & Choosers
The Microsoft.Phone.Tasks namespace includes classes used to configure and prompt the user to perform tasks either with no resulting data returned (a Launcher) or with returned data (a Chooser), e.g.
private EmailAddressChooserTask task = null;
public MainPage()
{
InitializeComponent();
// These two things must be in the constructor
task = new EmailAddressChooserTask();
task.Completed += new EventHandler(task_Completed);
}
void task_Completed(object sender, EmailResult e)
{
MessageBox.Show(e.Email);
}
private void button1_Click(object sender, RoutedEventArgs e)
{
// Causes application to terminate while task is performed
task.Show();
}
Application Bar
Each page can have an Application bar with up to four icon menu items and optionally additional pull-up text menu items (accessed by clicking ‘…’). See the sample code at the bottom of MainPage. xaml in a new project. Add a Click attribute to add a handler.
With Opacity of 1 the page size is reduced by the size of the bar. Opacity < 1 shows the bar over the page contents.

Accelerometer
Add a reference to Microsoft.Devices.Sensors and access information from an Accelerometer object.
private void StartAccelerometer()
{
accel = new Accelerometer();
accel.ReadingChanged += new EventHandler<AccelerometerReadingEventArgs>
(accel_ReadingChanged);
accel.Start();
}
void accel_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
{
// Access e.X, e.Y, e.Z & e.Timetamp
}
The values of X (right), Y (top), Z (face), range from 1 when the stated side points to the ground to -1 for the opposite side.
Location Services
The location system talks to the Microsoft location services to help establish a location. Usage is similar to the accelerometer using an add reference to Microsoft.Devices and the Microsoft.Devices.Sensors.GeoCoordinateWatcher class, which has a StatusChanged event and PositionChanged event (returning GPS data).
Use the optional constructor parameter to request high-accuracy data using the GPS receiver (taking longer to get a position and using more battery power). Otherwise, just available Mobile phone tower and Wi-Fi information is used.
Touch

<Grid x:Name=”LayoutRoot” Background=”#00FFFFFF”>
<tk:GestureService.GestureListener>
<tk:GestureListener Hold=”GestureListener_Hold”
DoubleTap=”GestureListener_DoubleTap” Flick=”GestureListener_Flick”/>
</tk:GestureService.GestureListener>
</Grid>
Push Notification Services
Microsoft’s Push Notification Services (PNS) provide a way for others (including the application developer) to send notifications to the application. Create a Microsoft.Phone.Notification. HttpNotificationChannel (or reopen an existing one) for the phone to receive notifications on behalf of the application. The channel is globally unique to the application instance combined with a channel name. The ChannelUri provided in the channel’s ChannelUriUpdated event should be sent to any party that needs to send notifications. The channel can receive Raw notifications (and optionally be configured to receive Toast and Tile notifications), which are sent to the PNS on the ChannelUri as simple xml+data packets.
| Notification Type | Detail |
| Raw | Up to 4096 bytes in a format agreed between parties. Presented to application by OS as event, if running, otherwise discarded. |
| Toast | Two strings. Presented to application by OS as event, if running. Otherwise, shown by OS as ‘toast’ overlay at top of screen (first string is Bold) and clicking it launches the application (with no knowledge of Toast). |
| Tile | A string, number, and image URL that will update the application tile if it was pinned to the Start screen by the user. The image URL must be either a relative URL for an image in the application deployment or be an internet URL under a domain permitted when Tile notifications were requested. |
If an error event occurs on the channel object, re-create the channel and inform any parties of the new URL.
DESIGN CONSIDERATIONS
Orientation
Set SupportedOrientations on a page as desired. Physical rotation of the devices causes the UI to be rotated if the new orientation is supported. To support both orientations, either build UI without absolute positioning (e.g., using ScrollViewer, text wrapping, scaling elements, and/or * width/height for Grid columns and rows) or support the OnOrientationChanged override to adjust UI layout.
Built-in Styling Resources
Resources like styles, brushes, widths, colors, fonts, and font sizes can be applied to UI elements in XAML using the syntax like FontFamily=”{StaticResource ABC}” where ABC is a resource defined in XAML or is one of the built-in styles available on the phone. The built-in resources are listed when picking the Apply Resource option on select properties in the Property window. Some resources dynamically change according to the theme chosen on the phone.

Submission Requirements
Be sure to check on the latest submission requirements at http://go.microsoft.com/fwlink/?LinkID=183220 before submitting an application to marketplace.
Check out the Design Resources for Windows Phone 7 at http://msdn.microsoft.com/en-us/library/ff637515(VS.92).aspx and short design tutorials at http://www.microsoft.com/design/ toolbox/school/tutorials.aspx.



