Hey guys. Today i am going to discuss about the MediaElement in Silverlight and see how we can put it in use in Silverlight and WPF applications. We can integrate media into our Silverlight pages and WPF UserControls.


MediaElement Objects

To add media to the Silverlight page just add a MediaElement to your XAML and provide a URI (Uniform Resource Identifier) to the media to play. The code below will show you how to create a MediaElement and set its Source proprty to URI of a video file. You can add the video file to Visual Studio project also and then set its property to Resource and the MediaElement will begin playing when the page loads.


<StackPanel Width="300" Height="300">
  <MediaElement x:Name="media" Source="xbox.wmv" Width="300" Height="300" />

Note – The MediaElement object can play WMV (Windows Media Video), WMA (Windows Media Audio), MP3 Files.
MediaElement Properties
The MediaElement object provides several media-specific properties. The following list describes the commonly used properties.

  • AutoPlay: Specifies whether the MediaElement should begin playing automatically. The default value is True.
  • IsMuted: Specifies whether the MediaElement is silenced. A value of True mutes the MediaElement. The default value is False.
  • Stretch: Specifies how video is stretched to fill the MediaElement object. Possible values are None, Uniform, UniformToFill, and Fill. The default is Fill.
  • Volume: Specifies the volume of the MediaElement object’s audio as a value from 0 to 1, with 1 being the loudest. The default value is 0.5.

In addition to its media-specific properties, MediaElement also has all the properties of a UIElement, such as Opacity and Clip.

Controlling Media Playback

You can control media playback by using the Play, Pause, and Stop methods of a MediaElement object.


         <ColumnDefinition Width="*" />
         <ColumnDefinition Width="*" />
         <ColumnDefinition Width="*"/>
         <RowDefinition Height="*" />
         <RowDefinition Height="Auto" />
    <MediaElement x:Name="media" Source="xbox.wmv" Width="300" Height="300" Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="3" />
    <!-- Stops media playback.-->
     <Button Click="StopMedia" Grid.Column="0" Grid.Row="1" Content="Stop" />
    <!-- Pauses media playback. -->
     <Button Click="PauseMedia" Grid.Column="1" Grid.Row="1" Content="Pause" />
    <!-- Begins media playback. --> 
    <Button Click="PlayMedia" Grid.Column="2" Grid.Row="1" Content="Play" />



private void StopMedia(object sender, RoutedEventArgs e)
private void PauseMedia(object sender, RoutedEventArgs e)
private void PlayMedia(object sender, RoutedEventArgs e)

Visual Basic

Private Sub StopMedia(ByVal sender As Object, ByVal e As RoutedEventArgs)
     media.Stop() End Sub
Private Sub PauseMedia(ByVal sender As Object, ByVal e As RoutedEventArgs)
     media.Pause() End Sub
Private Sub PlayMedia(ByVal sender As Object, ByVal e As RoutedEventArgs)
     media.Play() End Sub

Video Player Sample with Code

The following example illustrates typical features of a video player including playback control, a progress/seek slider, and full screen toggling.

Smooth Streaming

Smooth Streaming is an IIS (Internet Information Services) technology that enables adaptive streaming over HTTP to Silverlight clients.  Smooth Streaming breaks video feeds into small fragments which enables it to quickly alter the quality of the video, depending on the current bandwidth of the client.  This creates a high-quality viewing experience that scales massively on content distribution networks.   For more information on Smooth Streaming, see the IIS Smoothing Streaming site.

For an indepth example of Smooth Streaming, see the Microsoft Silverlight Media Framework CodePlex project.


Extending your Silverlight 4 Application with Controls

We could not only use and extend the controls present in the visual studio toolbox for Silverlight but also there are multiple providers offering additional controls for Silverlight framework.

Extending XAML

XAML stands for eXtensible Application Markup Language and hence it’s possible to add import external elements into a document without breaking rules.

Mapping a Prefix to CLR Namespace

Now we can define a set XML namespace (xmlns) in XML and can map a unique identifier to a prefix so that the XML parser can use additional rules while loading the document.

For Example

Lets say we want to add double value in the document resources. Now as you would know that XAML is by default configured for User Interface elements, the default XML namespaces will not map to Double types so we have to add the line of code shown in Bold in your XAML other than the normal code.


<UserControl x:Class="DoubleInResources.MainPage"







d:DesignHeight="300" d:DesignWidth="400">


<sys:Double x:Key="ButtonsWidth">200</sys:Double>


<Grid x:Name="LayoutRoot" Background="White">

<Button Width="{StaticResource ButtonsWidth}" Height="{StaticResource ButtonsWidth}" Content="Click Me!!" />




So we are including the mscorlib namespace which contains the Double type definition and then referencing the same in UserControl.Resources and then we have referenced the same as a static resource.


When we are working with XAML we encounter two types of namespaces

CLR Namespaces – Used in .NET code to group the classes logically.

XML Namespaces – Used to extend XML document with additional declarations.

Prefix is not always needed

Silverlight elements are defined into two namespaces. The first one is a Unique Resource Identifier (URI) mapped to the default xmlns (http://schemas.microsoft.com/winfx/2006/xaml/presentation).


In fact, multiple CLR namespaces (such as System.Windows.Controls, System.Windows.Shapes, and so on) are mapped to this URI. This allows us to use all the types within these namespaces without having to use a prefix. For example, we write <Button Click=”Button_Click” /> and not <anyPrefix:Button Click=”Button_Click” />. Note that this URI is not a website’s address, and entering it into a web browser will not lead you anywhere. It is just a Unique Resource Identifier, a unique name.


The other namespace used by Silverlight by default is http://schemas.microsoft.com/winfx/2006/xaml, another URI, which is mapped to the x prefix. Inside this namespace are defined additional properties that can be applied to any element.


How to add a namespace to any element

You can a namespace mapping to a control as well as shown below:

<Button xmlns:controls=”clr-namespace:MyApplication.Controls”>

<controls:MyControl />



How to define your own CLR and Mapping CLR Namespaces

We can map our own URI to a group of namespaces and this is useful because we can consolidate multiple CLR namespaces into one single URI and also this would hide the CLR namespaces that our code is using. And later when we decide to move some classes to different CLR namespaces we don’t need to change the XAML code. This is also very useful in creating data objects and it also makes data binding easier.

For Example:

Add the following code to the AssemblyInfo.cs


[assembly: XmlnsDefinition("http://www.mycompany.com", "DoubleInResources")]

[assembly: XmlnsDefinition("http://www.mycompany.com", "DoubleInResources.Controls")]

[assembly: XmlnsDefinition("http://www.mycompany.com", "DoubleInResources.DataAccess")]


And then after building the solution we can reference it as shown below:

What is a Control?

I know you would say that you know what it is but lets start with a formal definition of Control. A Control is an element of software, encapsulating some functionality related to user interface. Now in Silverlight there are two kinds of controls User Control and Custom Control.

User Controls

A user control is a logical group of other controls. It is typically used to separate a user interface in smaller parts that are easier to code and design. In fact, in Silverlight, all the pages of an application are user controls.

The App class (defined in App.xaml and App.xaml.cs) is the main point of entry for the Silverlight application. This is also where the MainPage control is created and assigned.

The Application_Startup Event Handler in App.xaml.cs is as follows:




If you rename the MainPage control to a different name, you must also change the name in the RootVisual assignment, or else your application will not compile anymore.


Custom Controls

The custom controls are made of code only as against XAML (Front End) and a code behind file. All controls build in Silverlight are lookless. The custom control file defines only the controls functionality i.e. Properties and methods and its behavior is defined by its states and parts.

For the controls to be visible, a XAML front end must be defined, though. An invisible control is not very usable! One control can have multiple appearances, defined in as many control templates. We talk out a separation of concerns: The control’s code defines its functionality; the control’s template defines its appearance. Typically, a developer implements the control, whereas a designer styles and templates it.


Design a Custom Control


Let’s take the example of a Custom with the following functionality:


  • The user defines a threshold and a value, both of type Double.
  • If the value is higher than the threshold, the control is in High state.
  • If the value is lower than the threshold, the control is in Low state.
  • If the value is equal to the threshold, the control is in Equal state.
  • Both the threshold and the value can change dynamically, be data bound, animated, and so forth.
  • The user can click one part of the control to increment the value by one unit, and another part to decrement by one unit.
  • The control can be disabled, in which case clicking does not change the value.


Now as you see we have the functionality of the custom control but not how the control will look so the developer can start working the designers can do the designing part simultaneously.


Let’s get started:


  1. In Visual Studio, select File, New, Project from the menu.
  2. In the Add New Project dialog, in the Silverlight category, select Silverlight Class Library.
  3. Enter the name CustomControlsLibrary and click OK. Make sure that you select Silverlight 4 in the next dialog. This creates an assembly, a library that can be referenced in multiple applications but cannot be run on its own.
  4. Delete the file Class1.cs in the Solution Explorer (because will not use it).
  5. Right-click the CustomControlsLibrary project in the Solution Explorer, and select Add, New Item from the context menu.
  6. In the Add New Item dialog, select the Silverlight, and then select a Silverlight Templated Control.
  7. Enter the name ThresholdControl.cs and click Add.

Defining the Parts and States

These steps create a C# code file, a folder named Themes, and a XAML file named

Generic.xaml. We will investigate this last file later; for now let’s declare the parts and

states for this control:

  1. Open the file ThresholdControl.cs.
  2. According to the requirements, the control has two state groups. We will call these the Common states (Normal, Disabled) and the Threshold states (High, Equal, Low). Note that the states within a state group are mutually exclusive; that is, the control cannot be simultaneously in Normal and in Disabled state. However, it can be Normal and High, or Normal and Low, and so forth. Defining the states and states groups is done with the TemplateVisualState attribute on the class.
  3. The requirements also state that the control has two parts with a special meaning: Clicking them increments or decrements the value. Here too, we use an attribute to define the parts on the class: the TemplatePart attribute.


The ThresholdControl.cs should look like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace CustomControlsLibrary
    [TemplatePart(Name = "IncrementPart", Type = typeof(UIElement))]
    [TemplatePart(Name = "DecrementPart", Type = typeof(UIElement))]
    [TemplateVisualState(GroupName = "Common", Name = "Normal")]
    [TemplateVisualState(GroupName = "Common", Name = "Disabled")]
    [TemplateVisualState(GroupName = "Threshold", Name = "High")]
    [TemplateVisualState(GroupName = "Threshold", Name = "Equal")]
    [TemplateVisualState(GroupName = "Threshold", Name = "Low")]
    public class ThresholdControl : Control
        public ThresholdControl()
            this.DefaultStyleKey = typeof(ThresholdControl);

        public double Value
                return (double)GetValue(ValueProperty);
                SetValue(ValueProperty, value);

    public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(double), typeof(ThresholdControl), new PropertyMetadata(0.0, OnValueChanged));

    public double Threshold
            return (double)GetValue(ThresholdProperty);
        SetValue(ThresholdProperty, value);

    public static readonly DependencyProperty ThresholdProperty = DependencyProperty.Register("Threshold", typeof(double), typeof(ThresholdControl), new PropertyMetadata(0.0, OnValueChanged));

    private static void OnValueChanged(object s, DependencyPropertyChangedEventArgs e)
        var sender = s as ThresholdControl;
        if (sender != null)

    private void GoToThresholdState(bool useTransitions)
        if (Value > Threshold)
             VisualStateManager.GoToState(this, "High", useTransitions);
            if (Value < Threshold)
                 VisualStateManager.GoToState(this, "Low", useTransitions);
                 VisualStateManager.GoToState(this, "Equal", useTransitions);
    public override void OnApplyTemplate()
        var incrementPart = GetTemplateChild("IncrementPart") as UIElement;
        if (incrementPart != null)
            incrementPart.MouseLeftButtonDown += new MouseButtonEventHandler(IncremementPartMouseLeftButtonDown);
        var decrementPart = GetTemplateChild("DecrementPart") as UIElement;
        if (decrementPart != null)
            incrementPart.MouseLeftButtonDown += new MouseButtonEventHandler(DecremementPartMouseLeftButtonDown);

    void IncremementPartMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    void DecremementPartMouseLeftButtonDown(object sender, MouseButtonEventArgs e)


And the Generic.xaml should look like this:





<Style TargetType="local:ThresholdControl">

<Setter Property="Template">


<ControlTemplate TargetType="local:ThresholdControl">

<Border Background="{TemplateBinding Background}"

BorderBrush="{TemplateBinding BorderBrush}"

BorderThickness="{TemplateBinding BorderThickness}">


<VisualStateGroup x:Name="Threshold">

<VisualState x:Name="High">






KeyTime="0" Value="0" />






KeyTime="0" Value="0" />









<ColumnDefinition Width="30" />

<ColumnDefinition Width="*" />

<ColumnDefinition Width="30" />


<Border Background="Blue" x:Name="DecrementPart"


<TextBlock Text="-" />


<StackPanel Grid.Column="1"



<TextBlock Text="{Binding

RelativeSource={RelativeSource TemplatedParent},Path=Value}" />

<TextBlock x:Name="HighTextBlock"

Text="&gt;" />

<TextBlock x:Name="EqualTextBlock"

Text="==" />

<TextBlock x:Name="LowTextBlock"

Text="&lt;" />

<TextBlock Text="{Binding

RelativeSource={RelativeSource TemplatedParent},Path=Threshold}" />


<Border Background="Red"




<TextBlock Text="+" />











You can find the complete Source Code at http://min.us/mKwMNIhKq

Lets learn about creating Windows Phone Projects

Visual Studio 2010

    • Visual Studio is an “Integrated Development Environment” for creating programs
      • Edit program source
      • Add and manage program resources
      • Build, deploy and debug an application
      • It can be used for multiple platforms and languages and can also be customized by plug-ins for the different target platforms

Windows Phone on Visual Studio

  • Create the Windows Phone Solution
  • Edit the program source files
  • Add and manage program resources
  • Build and run the solution
  • Debug the solution on emulator or device
  • Manage the properties of deployment in marketplace.

Visual Studio Project and Solutions

  • A .NET Program is made up of assemblies
    • An assembly is a library file(.dll) or an executable (.exe) and it contains compiled code and resources (e.g. images and sounds) along with a manifest.
    • The .exe file also contains an entry point (Main)
  • A Visual Studio solution project describes the content of a single assembly
  • A Visual Studio solution is made up of number of projects and at least one of them has an entry point where a program can start
  • A Visual Studio Solution is an XML file that contains reference to the project file that make up solution.
  • Each project contains resources and code which contains single project can be shared amongst multiple solutions also a library assembly can be used in the library.



  • New projects and solutions are created from templates installed in Visual Studio
  • Additional templates can be installed so that the tool can be used to target different platforms
  • These templates give you the basic structure of the type of program you are trying to make and also add the relevant references and saves you a lot of effort.

Making a Silverlight Application

  • Silverlight apps are generally line of business apps which are used to do business with and there is a template that helps us create a Windows Phone Silverlight application.
  • Very easy to create rich user interface.
  • This creates the initial page for our application and configures Visual Studio to target the Windows Phone platform.
  • If we want to create additional pages and add resources to the solution we can do this using Visual Studio.

Note – Windows Phone Mango is called 7.5 but the tools and the OS is called 7.1. The reason being the development team started pretty early and named the OS as 7.1 (after 7.0) but when the marketing team decided that they would call the whole package as 7.5

XNA Game Projects

  • Could be developed in a similar way to a Silverlight app but the starting template needs to be different.
  • The solution structure will be different though.

  • The content project contains all the elements of the game, assets, texts,etc
  • If you have not developed an XNA games before then i would like tell you that
    • An XNA game will not be like a silverlight app in which you press a button but in an XNA game the stuff will be repeated 30 times a second.
    • Its pain free and very well packaged.
    • XNA is great for writing games
    • Makes good use of graphics acceleration
    • Can be tedious to create UI behaviors

Combining Silverlight & XNA

  • It is possible for the silverlight form containing XNA content to hold silverlight components and this makes it possible to overlay Silverlight UI elements on top of an XNA display.
  • This makes it easier to build interfaces to XNA game.
  • Such a project will contain at least three projects
    • SilverXNA – It is the project that actually does the running
    • SilverXNALib – The libraries
    • SilverXNALibContent – XNA library content which will have assets, etc
    • When we make a silverlight and XNA combined program then we will have a page that will take us from the silverlight to XNA. So shown in the image below we will have a single button that will navigate to the game page on clicking.
    • Also this button click starts the XNA game engine.

  • The XNA page as shown below contains version of
    Draw and Update methods that are called to run the game within the silverlight

Multiple Project Solutions

  • A VS 2010 solution can have
    • PC version of XNA game
    • XBOX version of a game
    • Windows Phone Version of a game
    • They can also share code libraries which are also part of solution
    • Many projects can share the output from a single project.

Running Applications on Windows Phone Platform

Windows Phone Device Basics

To connect from a Windows PC to Windows Phone Device we need the Zune software. this could also

  • Synchronize Media
  • Perform Phone Updates
  • The download is available at http://zune.net
  • Before we deploy our application on Windows Phone we need to register it as a developer device. This registration is a one time process and the registered developers can register up to 3 devices (but registered students can register only one device).
  • Now you need to connect the phone to your PC and from the drop down as shown below we can select the Windows Phone 7 Device

  • The debugging method and development environment is the same for both the WP devices and Emulator.
  • The problems that you might face while deployment might be
    • If the phone is displaying lock screen deployment will fail.
    • Applications that use media will not work correctly if they are deployed when the Zune software is running. To solve this problem we can use “Windows Phone Desktop Pass- Through” program to connect instead of Zune. It is available with SDK.
    • Once the application is deployed it will be stored on the device for later use but remember at a time you can have only 10 of your own applications on the phone at any time. You can anyways send the compiled version of your application to other registered developers for them to use on their developer devices.

Emulator Basics

  • Emulator is available with Windows Phone SDK.
  • It runs as a program on the windows PC.
  • It has the same software as Windows Phone device but is targeted to run on Windows PC platform.
  • The Emulator
    • Has a browser
    • Will provide phone behaviors for things like placing calls and sending SMS. Also it has some entries in phonebook
    • Contains emulation of windows phone camera, GPS and motion sensors
    • Has the ability to capture screenshots of programs running on the phone.
    • If you are developing a game then it is recommended to run it on the phone as the performance is something which is not properly tested on emulator as it running in Windows environment.
    • You can use a PC mouse to touch on the screen.
    • If you have a multitouch monitor then that touch can be passed to the emulator as well.
    • If you want to use the PC keyboard for typing then you should use the Pause/Break key to toggle the emulator keyboard. When the Emulator keyboard is not there it will take the input from PC keyboard.
    • The windows Phone Emulator
      • Does not support Zune media playback.
      • Uses only only the built in browser application.
      • Should be used for functional testing only.
      • When you hover over the emulator with a PC mouse you will see an extra set of tools.
        • These allow you to rotate the emulator into different orientations
        • There are two landscape positions but only one portrait position.

  • The camera can also be emulated but it can take a simple photograph and return it.
  • Location Emulation also works now with Mango version. The location tab is shown below and you can click the location move the emulator to that position and also place pushpins to describe a route and then replay the route as well.

  • Windows Phones contains an accelerometer and compass that can be emulated as well for determining the position.

  • Also you can take screenshots in Windows Phone and the same can be emulated as well

Program Debugging

  • We can add breakpoints
  • We can use Single Stepping
  • We can use the Immediate Window


Your feedback and comments are welcome.



So the topics we are going to cover in this post are:

  • Windows Phone Task Management
  • Multi-Tasking with Background Agents
  • Creating tasks in Visual Studio
  • File Transfer Tasks
  • Background Notifications
  • Background Music Playback Tasks


  • Must have .Net and Silverlight development experience
  • Must have developed a windows phone apps.

Lets start


Windows Phone Task management

Forground Tasks

  • Normally a windows phone application runs in the foreground and interacts with the screen and user of the phone
  • There is only one foreground application active at a time though other may be running but are not active. This ensures better battery life for the user.

Background Tasks

  • A Windows Phone application can have only one background agent which can perform perodic tasks or resource intensive tasks or both.
  • The Agent can run when the application is not in the foreground.
  • The background tasks have limitations to what it can do and processor and other phone facilities. The logical reason that microsoft architect give is that if a background tasks goes out of control or does what it is not intended to do somehow it should not affect the battery life of the phone and the user user experience as well.
  • A background task can be used used to conatc the datbase and get the updates every half an hour or play music from a server online.

Background Agent Health Warning

  • There can only be limited number of background agents running at a point of time and this controlled by the oprating system.
  • A background agent will be started only when the operating system can give the agent processor resource.
  • If the phone goes to power saver mode then the background agents may stop running.
  • Also at any point of time the user can see the background tasks running and can manage them and choose to disable them.
  • So dont put any critical logic in background agent as it may not run. Its like icing on cake.

Multitasking with background agent

Agents and Tasks

  • The Agent is the container that is manged by the operating system and agent is the code that will run.
  • There are two kinds of tasks
    • Perodic
      • Will run every now and then (typicallyevery 30 minutes or so).
      • Intended to perform a task that runs regulary and complts quickly
      • Phone will have of limit on how many of them can be running.
      • Good for location tracking tracking and polling background services.
    • Resource intensive
      • Will run when the phone is in a postion to let them. This means it will run when
        • The phone is connected to mains
        • The phone is connected to Wi Fi
        • The phone is not being used (lock screen is displayed)
      • So if you rellay need this to run you need to made some recomendations to the user so that this resource intensive task runs successfully.
      • A Resource intensive agent can run upto 10 minutes.
      • Good for synchronization with host service, unpacking / preparing services, compressing database.

Dual Purpose Agents

  • An application can run both periodic and resource intensive tasks.
  • Can be achived though single background agent class.
  • When the agent start it can determine in which context it is running and behave appropriatly.

Creating tasks in visual studio

Creating an application

  • Lets Create a captians log application which will be a simple logging application.
    • Users can type log entries which are timestamped and stored in an isolated storage.
    • The tracking feature will be added using background agent.
    • The start tracking button click will fire up the background agent will be track the location of the captain and add it to the log. So the agent will update the position even when the program is not active.

  • Create a Windows Phone application solution and develop the foreground tasks and applications.
  • Add a new project to the application solution which is Windows Phone Scheduled task (VS Template). This will contain code will run when the agent is active.

  • Here is the solution file for the captians log which has got two projects:
    • Captians Log – The Windows Phone Silverlight Project which is the main application.
    • LocationTaskAgent – The background agent to perform the tracking.
  • Solutions may contain differnt projects and when the soltion is build all the assembly file outputs will be combined and sent to the phone.

  • Before this works we need to refernce the LocationTaskAgent Project in Captains Log

  • And when we do this the application manifest file adds a little bit of text to hold the description of the background agent and this is how the background agent is bound to the application. Here is the text added to the application manifest file.

  • So below is the code that will run when the agent wakes up so we need fill this OnInvoke method with our code that the agent will run. At the end to this code we need to call the method notify complete whcih will will notify the runtime system that it is done.

  • The Captains log datafile is shared between the application and agent and the first thing that the agent will do is load this datafile from the isolated storage.

  • Now we make use of GPS traking to find out the current loaction. So we make GeoCoordinateWatcher and start it and use it to get the location. Now before you start thinking about the performance hit this does i would like to tell you that there is a special version of this class provided for Background Agents which uses cached location data which is stored every 15 minutes.

  • And then agent just stores back this location to the application and goes to sleep.

  • Finally a notification is displayed to the user on which the user can click and go to the main application.

File transfer tasks

  • It is possible to create a background task to transfer files to and from application’s isolated storage.
  • The transfer will take place when the application is not running.
  • An application monitor the state of downloads and display their status
  • Files can be transferred from http or https hosts (ftp is not suppoerted currently)
  • The system maintains a queue of active transfers and services each one in turn.
  • Applications can query the state of active transfers.

Background Transfer Policies

  • Policies are :
    • Maximum upload file size is 5Mb
    • Maximum download file size over cellular (mobile phone) data : 20Mb
    • Maximum dowload file size over WiFi : 100Mb
  • These can be modified by settng the value of TransferPreferences on a particular File Transfer.

Background Transfer Namespace

  • The background transfer namespace is :

  • All the background transfer services are provided from the BackgroundTransfer namspace
  • Most instertingly you dont need to create additional projects to manage background transfers.

Create a Background Transfer

  • The following code creates a request and sets the source for transfer and it also sets the transfer method.

  • The following code sets the destination of the files transfer which is isolated storage of the application. Also it sets the preferences for the transfer. Now the transfer preferences can have multiple string so that you can set multiple properties.

  • The following code starts the transfer request by adding it to the list of active transfers. Also catches the exception if any and shows a message if it cannot proceed with the transfer.

  • The following code monitors the transfer by binding the methods to the events fired by the transfer request.


  • You can also kill the transfer by using the following code:

  • Windows phone appplication at any point of time can find out how many active transfers does have and as a rule of thumb you should always check the same whenever your application restarts because your transfers are still running when your application is not active. Below is the code that lets you do the same.

Scheduled Notifications

  • Windows phone app can create scheduled notifications and they are displayed when the application is running or not.
  • When the notification is diplayed the phone user has the option to respond to it or not. Also the notification can be liked to an application page.
  • The notifications can fire once or repeatedly at configurable intervals.
  • The notifications is maintained by phone operating system, once the application can started then it doen not have to do anything.

Sample Application

  • Lets make a simple timer application which will have two silverlight pages.
  • The user will set the time using the slider then preses the start timer button to create a notification.
  • When the notification will fire the 2nd page of the application which is egg ready page will be displayed and if the user clicks on the same then user will be taken to the application.
  • The sceen of the application will look something like this:

  • The code for the creating the reminder is as below. This code will create the reminder and then adds it as a sceduled service. The value eggTime holds the lenght of the delay and this code also sets the url of the page in application.

  • And before you add the reminder you need to check if its already present in the memory and if the that is the case it is removed from the memory. The code for doing that is as below:

Audio Playback Agents

  • It is possible to create a playback that will manage an application playlist and the mechanism is the same as for other background tasks.
  • The audio can be streamed or stored in application’s isolated storage.

  • This would also work pretty much like the things shown above in the post so i am not elaborating it.


You are free to ask any questions or leave your comments here…


Alright guys i am back with a new concept in Windows Phone 7 ( WP7 ) which is ViewStateManager. It is a really important concept for understanding visual states associated with them. If you want to create different states for your custom control then we would have to use Visual State Manager.

If you have the solution from my previous post then you can continue with it or you can download the solution here.

We will a few custom states and also learn about behaviours in this post.

  •  Now open CompanyLocations.xaml in expression blend. Drag four TextBlock controls onto the design surface, two for the headers and two for the details and then lay them out similar to the following snapshot.
Location Details

Location Details

  • Lets add a little more fun to this. Add two more textblock rotated at 90 degree and move the location details of the screen and also increase the font size of the headings as in the image below.
Text Rotation

Text Rotation

  • Now let’s go to the top left of expression blend where we have states and lets create new state group. Click on the Add State Group button and name the state group as LocationStates. Now add two new states namely CorporateState and SatalliteState. Now your state group should look something loke the screenshot below:

  • Now select CorporateState to start recording for that state which you can verify by seeing the red dot at the top right of the design surface. Now this will record any changes to the state as compared to the base state. Layout the CorporateState as shown in the image below:




  •  Layout for the SatelliteState is shown below:


  • Now lets switch back to the initial state and that any changes we make will affect all the states.
  • Now lets include behavior to bind these states to action. So now in your assets window search for GoToStateAction and drag and drop it to both the CorporateOffice and SatelliteOffice text.


  •  Now change the name to the GoToStateAction to the appropriate statename.