Skip to main content
August 15, 2013
Windows Phone Developer Blog

Creating a UI for Background Transfer Requests



This blog post was authored by Nate McMaster, a Program Manager Intern on the Windows Phone team.

– Adam


In the Windows Phone Toolkit – August 2013 update we add a TransferControl element to the set of XAML controls. You can use this control to more easily create a UI that shows the progress of a background transfer, either an upload or a download. The control also gives the app user the option to cancel a background transfer while it is in progress. Get the source code and sample in the Windows Phone Toolkit – look for the TransferControl sample on the main page after running the app.

TransferControl is your best tool for indicating background file transfer progress. The default style and behavior of this control follows Windows Phone UX guidelines. Using this control can help you make sure your app meets the requirements for certification. The Windows Phone Store requires apps to give the user the option to view and to cancel all active and pending background transfers (see requirement 6.10 in Additional requirements for specific app types for Windows Phone). This pre-built XAML control can help you more easily meet that app certification requirement.

In this post we demonstrate how to use TransferControl in a Windows Phone app, and how to customize its appearance and behavior.

XAML

Before you can add TransferControl to a page, you must add the Windows Phone Toolkit as a XAML namespace. To do this, add the following tag to your XAML page in your project solution:

XAML
  1. <phone:PhoneApplicationPage
  2. <!– … –>
  3. xmlns:toolkit=”clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit”
  4. >

Use the following XAML tag to add TransferControl to the page:

XAML
  1. <toolkit:TransferControl />

Default properties

A basic TransferControl has three visual elements, vertically stacked. At the top is the header, a TextBlock element that displays the filename of the background transfer.

Beneath the header is a progress bar. The progress bar is visible only when an associated transfer is uploading, downloading, or is paused. The progress bar is hidden when the transfer is pending, has failed, or is finished.

At the bottom of the stack of elements, a smaller TextBlock element shows a short message that displays the status of the transfer, for example, downloading, failed, or complete. All of these strings have been localized to the 51 languages supported by all controls in the Toolkit.

Each element also has a context menu. Users can see available actions on the context menu by pressing and holding on any area of the TransferControl element. Currently, the only action available in the context menu is Cancel.

TransferMonitor

Before you use a TransferControl, you need to associate it with an instance of TransferMonitor. This object acts as a wrapper around a BackgroundTransferRequest, and handles the logic of updating the UI and adding and removing the request to the background transfer service queue.

clip_image002
clip_image004

The simplest use of the control is to show a background file transfer. TransferMonitor creates an instance of BackgroundTransferRequest. TransferControl must be assigned to this instance. Once assigned, the data binding updates the UI.

Page.xaml

XAML
  1. <toolkit:TransferControl x:Name=”Control1″ />

Page.xaml.cs

C#
  1. var request = new BackgroundTransferRequest(new Uri(“http://contoso.com/episode20.mp3”, UriKind.Absolute), new Uri(“/shared/transfers/episode20.mp3”, UriKind.Relative));
  2. var monitor = new TransferMonitor(request);
  3. Control1.Monitor = monitor; //Assign the monitor to the XAML control
  4. monitor.RequestStart(); //This adds request to the BackgroundTransferService queue.

TransferMonitor also will accept a second argument, name, which will be the fallback value for the header text when it is not defined in the XAML declaration.

C#
  1. var monitor = new TransferMonitor(request, “Episode 20”);

Using TransferControl in a list

Another common scenario for using this control is to show multiple background file transfers. Using a generic collection of background transfer requests, a developer can easily create a queue or list of all transfers.

TransferMonitor can be assigned to a corresponding XAML element using data binding. This is useful when displaying a list of several background transfers. For example, if given a list of TransferMonitor objects, LongListSelector could be used to display all the objects.

Page.xaml

XAML
  1. <LongListSelector x:Name=”AllRequestsListBox”>
  2.     <LongListSelector.ItemTemplate>
  3.         <DataTemplate>
  4.             <toolkit:TransferControl Monitor=”{Binding}“/>
  5.         </DataTemplate>
  6.     </ LongListSelector.ItemTemplate>
  7. </LongListSelector>

Page.xaml.cs

C#
  1. var ListOfAllMonitors = new ObservableCollection<TransferMonitor>();
  2. foreach (BackgroundTransferRequest request in BackgroundTransferService.Requests)
  3. {
  4.     var monitor = new TransferMonitor(request);
  5.     ListOfAllMonitors.Add(monitor);
  6. }
  7. AllRequestsListBox.ItemsSource = ListOfAllMonitors;

Customizing appearance

The following code demonstrates how to modify the appearance of TransferControl:

XAML
  1. <toolkit:TransferControl Header=”Podcast” Icon=”/Images/Seattle.jpg” AutoHide=”True” StatusTextBrush=”Maroon”>
  2.     <toolkit:TransferControl.HeaderTemplate>
  3.         <DataTemplate>
  4.             <StackPanel>
  5.                 <ContentControl Content=”{Binding} HorizontalAlignment=”Left” />
  6.                 <TextBlock Style=”{StaticResource PhoneTextSmallStyle} Text=”Episode 20″ Margin=”0″/>
  7.             </StackPanel>
  8.         </DataTemplate>
  9.     </toolkit:TransferControl.HeaderTemplate>
  10.     <toolkit:TransferControl.ProgressBarStyle>
  11.         <Style TargetType=”ProgressBar”>
  12.             <Setter Property=”Foreground” Value=”Gold”/>
  13.             <Setter Property=”Background” Value=”Maroon”/>
  14.         </Style>
  15.     </toolkit:TransferControl.ProgressBarStyle>
  16. </toolkit:TransferControl>

This declaration creates a control that has customized the header section, the colors of the status text, and the progress bar. In addition, when the transfer completes, the control automatically hides.

clip_image006

Let us now deep dive into the individual properties of TransferControl that help with customization. There are five attributes that modify the appearance of the UI, and one attribute, AutoHide, which changes the behavior of the object.

Icon

TransferControl attribute
  1. Icon=”/Images/Seattle.jpg”

The Icon attribute adds an image that appears to the left of the header and progress bar. Setting the Icon property as shown in the above XAML will uniformly stretch the image to fill a 99 × 99-pixel area. It also creates a margin between the image and the progress bar. The value of the Icon attribute must reference a valid URI. You can use this URI to display an image from within the project or to download it from an external location.

Header

TransferControl attribute
  1. Header=”Podcast”

The Header property is where you define what appears above the progress bar. If you do not specify this property, the value of TransferMonitor.Name will be displayed by the monitor. This value is either an assigned string or the filename of the transferring file. If you don’t use HeaderTemplate to set the text style, the text is displayed using PhoneTextTitle2Style.

HeaderTemplate

HeaderTemplate
  1. <!– … –>
  2. <toolkit:TransferControl.HeaderTemplate>
  3.     <DataTemplate>
  4.         <StackPanel>
  5.             <ContentControl Content=”{Binding} HorizontalAlignment=”Left” />
  6.             <TextBlock Style=”{StaticResource PhoneTextSmallStyle} Text=”Episode 20″ Margin=”0″/>
  7.         </StackPanel>
  8.     </DataTemplate>
  9. </toolkit:TransferControl.HeaderTemplate>
  10. <!– … –>

You can use HeaderTemplate to change the way the header appears above the progress bar. HeaderTemplate must be a DataTemplate type. In XAML, this is best declared by nesting the property. In this sample, HeaderTemplate is set to create a two-line header, but you can use any valid DataTemplate.

StatusTextBrush

TransferControl attribute
  1. StatusTextBrush=”Maroon”

Status text is the small phrase or word that appears beneath the progress bar. Its default color is the phone theme foreground color. You can modify this by setting StatusTextBrush to any Brush value.

ProgressBarStyle

ProgressBarStyle
  1. <!– … –>
  2. <toolkit:TransferControl.ProgressBarStyle>
  3.     <Style TargetType=”ProgressBar”>
  4.         <Setter Property=”Foreground” Value=”Gold”/>
  5.         <Setter Property=”Background” Value=”Maroon”/>
  6.     </Style>
  7. </toolkit:TransferControl.ProgressBarStyle>
  8. <!– … –>

You can use ProgressBarStyle to define the progress bar within the TransferControl. In the above sample, the style defines a new foreground and background color for the progress bar.

AutoHide

TransferControl attribute
  1. AutoHide=”True”

AutoHide by default is set to false. When it is set to true, the Visibility property of TransferControl is set to Collapsed when the transfer raises the Complete event.

TransferMonitor: Interacting with background transfer

TransferMonitor provides methods and events that help simplify interaction with the BackgroundTransferRequest.

RequestStart() and RequestCancel()

RequestStart adds the request to the background transfer service queue. RequestCancel removes the request from the queue. It is important to note that these methods only attempt to add or remove the transfer from the queue; they don’t guarantee that it will be successful. If the attempt is unsuccessful, the Failed event will be raised (see Events below). This behavior relies on BackgroundTransferService and the error messages generated when BackgroundTransferService.Add() and BackgroundTranfserService.Remove() fail to add a transfer to the queue.

Events

All events are raised with BackgroundTransferEventArgs. This class contains the Request property, which is set to the request for which the event was raised.

Started

This event is raised when the request is successfully queued to begin transferring. This means the background transfer service will run the transfer once the correct resources are available. If there are already resources available, this event is raised when the downloading or uploading begins. If not, the event will still be raised, but the transfer may be in a paused state, for example, waiting for a Wi-Fi connection or for the battery to be recharged

Failed

This event is raised when the transfer is canceled or when it fails, for example, due to a network connection error or timeout. When the event is raised, TransferMonitor.ErrorMessage is set to indicate why the transfer failed.

ProgressChanged

This event is raised when the transfer makes any progress downloading or uploading the file. This event is triggered periodically while the transfer occurs.

Complete

This event is raised when the transfer has successfully finished uploading or downloading the request. If the transfer requested a download, the file is available in isolated storage.

Conclusion

This is an overview of how you can use the TransferControl and TransferMonitor together to create a UI for background transfer requests. For even more information, see the source code at the Windows Phone Toolkit page on CodePlex.

TransferControl Reference

Classes

TransferControl

Inherits from System.Windows.Controls.ContentControl

Constructors

Name

Description

TransferMonitor

Initializes a new instance of TransferControl and applies the default control template.

Methods

None.

Properties

Name

Description

AutoHide

Gets or sets how the control visibility responds when the associated TransferMonitor raised its Completed event.

Header

Gets or sets the text that appears above the progress bar.

HeaderTemplate

Gets or sets the DataTemplate that defines the area above the progress bar.

Icon

Gets or sets the URI to an image to display.

IsContextMenuEnabled

Gets or sets if the context menu is enabled.

Monitor

Gets or sets the associated TransferMonitor.

ProgressBarStyle

Gets or sets the style used for the progress bar.

StatusTextBrush

Gets or sets the brush used for the status text.

Events

None.

TransferMonitor

Constructors

Name

Description

TransferMonitor(BackgroundTransferRequest)

Initializes a new instance of TransferMonitor with the specified background transfer request.

TransferMonitor(BackgroundTransferRequest,string)

Initializes a new instance of TransferMonitor with the specified background transfer request and a name.

Methods

Name

Description

RequestCancel

Removes the request from the queue.

RequestStart

Adds the request to the background transfer service queue.

Properties

Name

Description

BytesTransferred

Gets the number of bytes sent or received.

ErrorMessage

Gets the error message when the transfer fails.

IsProgressIndeterminate

True if the total size of the transfer is not known. False when the size is known.

Name

Gets or sets the name of the transfer.

PercentComplete

Gets the percent of the transfer that has completed. Returns a number between 0 and 1.

State

Gets the state of the transfer.

StatusText

Gets a string containing to message explaining the state of the transfer.

TotalBytesToTransfer

Gets the number of bytes that will be sent or received

TransferType

Gets the type of transfer (upload or download).

Events

Name

Description

Complete

Occurs when the transfer has finished uploading or downloading.

Failed

Occurs when the transfer is canceled or when it fails.

ProgressChanged

Occurs when the progress of the transfer changes.

Started

Occurs when the request has been successfully queued to begin transferring.

Enumerations

TransferRequestState

Value

Description

Complete

The request is complete.

Downloading

The request is downloading a file.

Failed

The request has failed.

Paused

The request is paused.

Pending

The request is waiting to begin

Unknown

The request is in an unknown state.

Uploading

The request is uploading a file.

Waiting

The request is waiting for the system.

TransferType

Value

Description

Download

Indicates a transfer that downloads a file.

Upload

Indicates a transfer that uploads a file.