Developing a Windows Phone 7 List Control

WindowsPhone8StartScSet1_Page

Download :  WP7JumpList2 (1)

JumpListBasic.png

Introduction

About a month ago, I created a Jump List control for Windows Phone 7 and published it on my blog. I got a lot of great feedback from the control, including questions about how certain parts of it work. As a result, I decided to publish an in-depth article here on CodeProject which describes the development of this control.

The control itself is quite dynamic, so the best way to get a feel for what it is like is to watch the following videos, one which is recorded from the emulator, the other on a real device – demonstrating the good performance of this control (apologies for the poor video quality!)

<OBJECT type=”application/x-shockwave-flash” codebase=”http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=3,0,0,0″ WIDTH=”480″ HEIGHT=”390″ data=”http://www.youtube.com/v/hdd1bIdSA-g?fs=1&hl=en_US”></OBJECT>

<OBJECT type=”application/x-shockwave-flash” codebase=”http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=3,0,0,0″ WIDTH=”480″ HEIGHT=”390″ data=”http://www.youtube.com/v/jk7jUeNNSHU?fs=1&hl=en_US”></OBJECT>

If you just want to grab the code and use the jump list in your application, then pop over to my blog where you will find a user guide and a number of examples. If you want to learn about how this control was put together, then read on …

Contents

Introduction

For Silverlight developers, Windows Phone 7 is a dream come true, a mobile platform that supports a language / framework they already know, or as Jesse Liberty puts it, “You are already a Windows Phone Developer“. What I find really cool about Silverlight for WP7 is that exactly the same controls can be used both on the web and the mobile. However, the controls for Windows Phone 7 are tailored specifically for the mobile form factor having larger areas to ‘hit’, and gestures for scrolling for example. Despite this, there are times when you really need a control that is specific to the mobile platform.

Navigating long lists of data is a chore on a mobile device. On the desktop / web, you can click on the scrollbar and navigate the full length of the list with a single gesture, whereas navigating the same list on a mobile requires multiple swipe gestures. This is where a Jump List comes in handy!

A Jump List groups the items within the long list into categories. Clicking on a category heading (or jump button) opens up a category view, where you can then click on one of the other categories, immediately causing the list to scroll to the start of this newly selected category.

This article describes the development of a Jump List control.

Developing the JumpList control

Creating a custom control

The first step when building a new control is to determine a suitable starting point, i.e., an existing framework class to extend. The jump list should support selection, so the framework Selector class (which ListBox subclasses) is a potential; however, it does not expose a public constructor, so that is a nonstarter! This just leaves Control, so we’ll just have to start from there:

By extending Control, we are creating a ‘custom control’ (or as the Visual Studio ‘Add New Item’ dialog confusingly calls them, ‘Silverlight Templated Control’). The ‘look’ of the control, i.e., the various visual elements that are constructed to represent the control on screen, are defined as a Style:

Setting the DefaultStyleKey of the JumpList in the constructor to reference the style above ensures that this style is applied to any JumpList instance that we create. The style sets a single property of the control, the Template, to render a Border. The various properties of the Border are bound to various properties that we have inherited from Control. The JumpList control doesn’t really do much yet, although we can create an instance and set its various border properties:

control.png

Rendering the items

The JumpList needs to render a collection of items that the user supplies, where each item is rendered according to a template, mimicking the behavior of ListBox (and other classes that render lists of objects, such as ComboBox). To support this, we add an ItemsSource dependency property of type IEnumerable to the control. If you have created your own dependency properties before, you will know that there is quite a bit of boiler-plate code to deal with, which is why I prefer to use code-generation rather than add this code manually or via snippets. The technique I am using here is described in the blog post ‘declarative dependency property code generation‘, where you simply add an attribute to your class describing the property, and the code-generation adds the required code to a generated partial class.

Adding a dependency property is as simple as this …

which results in the generation of the following code:

In order to render the list of items that the user supplies via the ItemSource property, we also need to expose a property that allows the user to specify how they want their items rendered. Following with the ItemsControl naming conventions, we’ll add an ItemTemplate property to the JumpList:

Again, the dependency property itself is added to the T4 template code-generated partial class.

In order to render the items that the user supplies to the ItemsSource property (either by binding or by directly setting the property), we need to somehow add them to the visual tree of our JumpList when it is rendered. We could add them directly to the visual tree at runtime; however, the framework ItemsControl provides a mechanism for rendering a bound collection of items within a panel, providing a simpler and more flexible solution. A collection of ContentControls are created in the code-behind, one for each of the bound items (later, this collection will also include group headings as well as the items themselves):

When the ItemsSource property of the JumpList is set, the above method, RebuildCategorisedList, creates a list of ContentControls which the JumpList exposes via the FlattenedCategories property. All we have to do now to add them to the visual tree of our JumpList is add an ItemsControl to the template, binding it to the FlattenedCategories property via a RelativeSourceTemplatedParent binding.

Our control is now able to render a collection of items, for example, if a JumpList is instantiated with the following template, where the ItemsSource is a collection of Person objects (with properties of Surname and Forename):

The JumpList would render as follows:

control2.png

Handling CollectionChanged events

The ItemsSource property is of type IEnumerable, which is the only requirement we have on the supplied data in order to render it. This gives the user great flexibility; they can supply a List, Array, or assign the ItemsSource directly to the result of a LINQ query. However, they may also set (or bind) this property to an ObservableCollection, with the expectation that the JumpList is updated when they add or remove items from the list. In order to support this requirement, we need to ‘probe’ the ItemsSource to see if it implements INotifyCollectionChanged (the interface that makes ObservableCollection work), and update our list accordingly:

Note that the above code could be optimized to inspect the NotifyCollectionChangedEventArgs.Action parameter, modifying our exposed list, rather than completely rebuilding it where appropriate.

Adding categories

So far the control simply renders the list of items, doing nothing more than an ItemsControl would. In order to make this into a jump list, we need to assign items to categories. In order to provide flexibility regarding how items are assigned to categories, we give the user of the control this responsibility via the ICategoryProvider interface:

Adding a dependency property to our control:

A category provider is responsible for assigning each object within the list to a category, and also for providing a list of all the categories. The list of categories might depend on the list being rendered, e.g., the dates of events, or it might be some fixed list, e.g., letters of the alphabet. The following shows an implementation of this interface which assigns items to categories based on the first letter of a named property, PropertyName. The category list is the complete alphabet, in order:

Here you can see that the category list is always the full alphabet and does not depend on the items that are currently rendered by the JumpList. The user of the control can simply set the CategoryProvider to an instance of the provider above. For example, if the control is being used to render Person objects (which have properties of Surname and Forename), the XAML for the JumpList would be as follows:

The RebuildCategorisedList method described above which creates a list of ContentControls, one for each item in the list, can now be updated to add the category headings (i.e., the jump-buttons). We want the user of the JumpList to be able to style these jump buttons, so some further dependency properties are added:

These three properties give the user complete control over how the buttons are rendered; if they want to simply set the width, height, or some other basic property, they can set the JumpButtonStyle; if they want to change the template, or add an icon for example, they can set the JumpButtonTemplate; finally, they can specify how the ‘object’ that represents each item’s category is rendered via the JumpButtonItemTemplate, this allows them to format a date, for example.

The RebuildCategorisedList is expanded to group the items based on the category provider via a simple LINQ query. Buttons are added to the collection of objects exposed to the ItemsControl within the JumpList template:

Note that a Button.Click event handler is added to each of the buttons that are created – more on this later!

We can set the default values for the three jump-button properties by adding property setters to the JumpList default style (in the generic.xaml file):

As you can see from the above XAML, the JumpButtonStyle and JumpButtonItemTemplate property values are quite simple. The JumpButtonTemplate is a little more complex; here we are defining the template used to render our buttons. Rather than using the default button template, which is black with a white border, the jump buttons are templated to be a solid rectangle filled with the phone’s accent colour (a user-specified colour which is used for live tiles etc…). The VisualStateManager markup has a single VisualState defined which makes the button turn white when it is pressed.

The control is now starting to look like a jump list …

control3.png

The Category view

When a user clicks on a jump button, we want to display a menu which allows them to jump to a specific category. In order to achieve this, we need to create another ‘view’ of our data which is hidden, revealing it when a button is clicked.

We can expand the method which builds our categorized list of items and jump buttons to expose a list of categories:

The above code creates a list of buttons, one for each category. The enabled state of each button is determined by whether there are any items within this category in the user-supplied list. Again, we allow the user to specify how the button is rendered via the template, style, and item-template properties.

The following markup is added to the template, binding an items control to a CategoryList property, using the same technique as the items control which renders the jump list:

The style, item-template, and template for the category buttons are similar to those of the jump buttons; however, the category button adds extra styling for the Disabled state, rendering the button in a dark gray colour. The above markup arranges the buttons using the Silverlight Toolkit WrapPanel, which gives the following result:

control4.png

Switching views

The control now has two different ‘views’, one which is the categorized list of items together with jump-buttons, and the other, the category view. All we have to do is handle the Click event on the jump-buttons to show the category view. For greater flexibility, this behavior is exposed via a bool IsCategoryViewShown property. When a jump-button is clicked, this property is set to true, and the change handler for the property takes care of switching the view. This provides greater flexibility to the user of the control, allowing them to switch views programmatically.

In order to show / hide the category views and list views that are defined in the JumpList template, we need to obtain references to them. With UserControl, elements named with the x:Name attribute are automatically wired-up to fields in the corresponding code-behind class. However, with custom controls, you have to do this wire-up yourself. The following code locates the ItemsControls for the jump list and category view:

Note: the name passed to GetTemplateChild matches the x:Name for each of these elements.

The code generated for each dependency property adds a call to a partial method which is invoked when the property changes. This allows you to add logic that is executed as a result of the property change. The following method is invoked each time the IsCategoryViewShown property is changed, it simply shows / hides the items control:

Making the jump

We have already seen that the method RebuildCategorisedList adds a Click event handler to the category buttons. We now need to add the code which makes the list ‘jump’ to the required location. The ItemsControl which renders our list of categorized items uses a VirtualizingStackPanel as the container for the items, and places this within a ScrollViewer. The VirtualizingStackPanel has a method SetVerticalOffset which can be used to scroll it to a specific index, allowing us to make the list jump.

The first thing we need to do is locate the VirtualizingStackPanel. Unlike the other named elements in our template, this element cannot be retrieved by GetTemplateChild within OnApplyTemplate because it is in a different XAML namespace (also, it may not be created initially, if the ItemsControl does not have any items to render). In order to locate the VirtualizingStackPanel when we need it, we can use LINQ-to-VisualTree to query the descendant elements of our ItemsControl to locate the element of the required type:

When a category button is clicked, we find the corresponding jump-button (both have the same Content, i.e., the category returned by the ICategoryProvider). Once the corresponding button is found, we can find its index, offset the VirtualizingStackPanel, then switch back to the jump-list view:

We now have a fully functioning JumpList control!

Jazzing it up!

The control we have developed so far works well; however, it is lacking in flare (we don’t want our iPhone and Android friends to think theirs is a better platform, do we?). We could spice up the graphics, adding drop shadows, gradients, images etc… however, that is not really in keeping with the Windows Phone 7 Metro theme which favours clear typography and sparse graphics coupled with fluid animations. In this section, we will look at how to make this control more visually appealing via animations, whilst maintaining its clean and simple style.

Simple Show / Hide animations

When the jump list control switches between the category and list views, the following code simply shows / hides the respective items controls for each of these views:

It would be nice if we could use a fade or some other transition effect to switch between these two views. A while back, I wrote a blog post which presented a couple of simple FrameworkElement extension methods, Show() and Hide(), which inspect the element resources to find a storyboard which can be used to show or hide the element. If no storyboard is present, the Visibility property is set instead. Applying this method, the above code becomes:

Here is the updated XAML for the ItemsControl which renders the jump list, to include storyboards which alter the control’s opacity in order to provide a fade-in / fade-out effect:

For details of the Show() / Hide() extension methods, please refer to my earlier blog post.

Adding a Loading indicator

If you have only developed Windows Phone 7 applications using the emulator, you will probably have some false impressions regarding your application’s responsiveness. The real Windows Phone 7 hardware is typically much less powerful than the emulated hardware on your whizzy developer machine! I made a few measurements and found that my developer machine emulator rendered each page approximately four times faster than a real device. However, results will of course vary from one machine to the next. The real take-home message here is, “test on the real hardware”. This section describes a few simple changes to the jump list which should ensure a rapid initial render time.

If the category view ItemsControl is shown by animating its opacity from 0 to 1.0, then all the visual elements of the category view will be rendered when the jump list is first displayed, even though the user cannot see the category view. This can add as much as half a second to the overall load time of the control. If the visibility of the ItemsControl is initially set to Collapsed (in generic.xaml), then the overhead of the numerous child elements it contains will be removed. However, this still does not remove the half-second additional render time for the category view, it just postpones it until later on. We do not want the jump list to simply ‘stall’ the first time a button is clicked, therefore a small loading indicator is added so that the user knows that the phone is doing something …

When a category button is clicked, we initially show a simple loading message, then set the category view visibility to Visible, causing the expensive initial construction of this view. When the category view and its child elements are created, a LayoutUpdated event will fire; we can handle this event in order to hide the loading indicator.

This simple loading indicator is added to the jump list template:

The code which handles the IsCategoryViewShown property changed is updated to show this loading indicator the first time the category view is shown. The next time it is shown, we do not need the loading indicator because the category view UI is already built and has just been hidden by setting its opacity to zero.

I have refined the above into a more general approach to deferring the rendering of some UI elements, creating a DeferredLoadContentControl which initially displays a ‘loading…’ message whilst the more complex content is constructed. You can read about this control on my blog.

Animating the ‘jump’

The jump list control described so far sets the vertical offset of our list directly so that the jump button which heads each category is immediately brought into view. In this section, we will look at how to animate this, so that the selected category scrolls smoothly into view.

The vertical offset of our list is changed via the following code:

Unfortunately, the vertical offset is not exposed as a dependency property, so we cannot animate it directly via a storyboard. A simple solution to this problem is to add a private dependency property to our jump list control which we can animate. We can then handle the property changed callback for this dependency property in order to set the vertical offset as above.

Here’s the private dependency property, with the callback that sets the vertical offset:

We can then create a suitable storyboard in the constructor of the jump list control. Here, a simple DoubleAnimation which uses a Sine easing function, which accelerates at the start and decelerates at the end (providing a smoother experience), is created:

We can make this functionality more flexible by adding a ScrollDuration dependency property to the JumpList control. All that is left to do is use the above animation when the category button is clicked:

Animating the category button ’tiles’

The switch from the jump list to the category view is now a bit more interesting, with a fade-effect applied (which can be replaced by some other effect if you re-template the control). However, it would be much more exciting if each of the category buttons were animated into view, in much the same way that the tiles on the Windows Phone 7 hub are animated.

To support this, the category button template is extended, adding storyboards for showing and hiding the category buttons, in much the same was as the Show() / Hide() extension methods described above. In the example below, a storyboard is defined that shows the category button by scaling and rotating the tile, with the reverse being used to hide it:

In order to play the above animation to reveal the tiles, we have to locate the storyboards that will be created for each tile. In order to make the ‘reveal’ effect more interesting, the following code ‘prepares’ each of the category tile storyboards by setting their BeginTime property based on the desired delay between the animations for neighboring tiles firing:

In order to reveal the category view, we simply iterate over all the tiles, firing the animations:

This gives the control a much more interesting transition between the two views:

JumpListAnimation.png

Note that the way this category view animation has been introduced means that the client of the control can change the animation by simply providing an alternative CategoryButtonTemplate.

Summary

This brings us pretty much to the end of this article. I hope your have enjoyed reading about the development of this control. If you use it in your Windows Phone 7 application, please let me know by leaving a comment below. Also, as mentioned earlier, if you want to read a user-guide or see some more practical examples of this control, please visit my blog.

Today the Windows Phone team released the final bits for Windows Phone 7!  The tooling is free and will integrate with Visual Studio 2010 and Expression Blend 4 if you have them installed as well.  Head over to

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=04704acf-a63a-4f97-952c-8b51b34b00ce
to get the RTM tooling.

Here is also a little list I’ve been keeping with useful controls around the internet!

Controls

Random Resources

Silverlight Tool kit

GestureService/GestureListener

ContextMenu

DatePicker

TimePicker

ToggleSwitch

WrapPanel

http://bit.ly/aBZWSQ

Wheel Control

http://bit.ly/bDcyFL

Swipe Title

http://bit.ly/balUu1

Picker (Combo box)

http://bit.ly/coyJ1F

Progress Bar

http://bit.ly/aAWd4K

More Complex splash screen

http://bit.ly/bGH93w

Touch tilting

http://bit.ly/bptbs9

Clearable Textbox

http://bit.ly/csSidM

Image Caching

http://bit.ly/cktA7N

Great list of resources

http://bit.ly/bVvIRn

Detect if a listbox is done scrolling

http://bit.ly/b1WfPO

Pass data between pages

http://bit.ly/akIzLO

relative date time converter

http://bit.ly/9F0gzP

Phone Styles

accent color would be Style=”{StaticResource PhoneAccentBrush}”

http://bit.ly/cUmhGi

Leave a Reply