Colin Eberhardt's Adventures in .NET

FastClick for WP7 – Improving Browser Responsiveness for PhoneGap Apps

January 5th, 2012

I recently released an update of the HTML5 / PhoneGap application I wrote a few months ago to the marketplace. This update fixed the location detection issue, where the marketplace certification process failed to detect that the application was using geolocation data via the browser (this issue has been fixed in PhoneGap 1.2), plus a few cosmetic improvements.

This application still exhibits a few UI quirks that make it fairly obvious that this is not a native application, the first is the gray box that appears whenever a link is clicked, the second is the overall responsiveness – there is a short delay between clicking on links / buttons and the application responding. It is this responsiveness that I would like to tackle in this blog post. This delay unfortunately gives the impression that your application is less responsive than it actually is!

So where does this delay come from?

Despite the rise in popularity of touch interfaces, much of the web is still designed for interaction with a mouse and keyboard, with the DOM exposing events for mouse-up, mouse-down and click user interactions. The Windows Phone 7 browser control captures touch interactions and translates these into the required mouse events, firing them on the DOM element being interacted with. However, the browser itself also needs to support gestures such as pan, pinch-zoom and double-tap zoom.

If we consider for example the pinch-zoom feature, where the user places two fingers on the screen and moves them apart in order to zoom in. It is highly unlikely they will place both fingers on the screen simultaneously. If, when the first finger was placed, a mouse-down event was fired on the relevant DOM element, there would be no way to ‘cancel’ this event when the user’s second finger made contact with the screen shortly afterwards. For this reason the WP7 mobile browser does not properly support mouse-down / mouse-up events. You will find that mousedown, mouseup then click are always fired immediately in that order regardless of how long you hold your finger on the screen for. Clearly the need to add gesture support to the browser interferes with the way in which native touch events are translated into JavaScript mouse events.

Now consider the double-tap zoom feature, where the user taps twice in quick succession to zoom the web page by some fixed amount. If the DOM click event were fired on the first tap, this would cause a navigation to occur if an anchor element were tapped. This is certainly not the desired behaviour! Again, there is no way to ‘cancel’ an event once it is fired, so the only solution to this problem is, when the user first taps the screen, pause for a few hundred milliseconds to see if they tap a second time. Only after this pause is it safe to pass the interaction onto the DOM, firing a click event on the relevant DOM element.

Stock image courtesy of lovetheson

The need to handle gestures in the native layer causes numerous issues for the browser event handling. Thankfully these issues are relatively minor for most websites, but if your aim is to create a HTML-based application with a native look and feel, these issues become quite major.

Improving responsiveness

The problem I want to tackle in this blog post is that of the click DOM event firing delay to support the double-tap gesture. With HTML5-based applications you will typically want to disable pinch zoom, double-tap zoom and (optionally) scrolling as I described in a previous blog post. As a result your application has no need for the double-tap and pinch gestures and we are safe to short-circuit this behaviour, immediately raising DOM click events when the user taps the screen.

My solution follows a similar approach to the utility class I wrote for suppressing pan / zoom, where event handlers are added to the Border that sits within the WebBrowser control visual tree:

\-WebBrowser
  \-Border
    \-Border
      \-PanZoomContainer
        \-Grid
          \-Border (*)
            \-ContentPresenter
              \-TileHost

In order to forward Tap gestures to the browser, we can add event handlers to the Border element, then use InvokeScript to pass this onto the DOM rendered within the TileHost.

The JavaScript code to achieve this is very simple, the DOM exposes an elementFromPoint function which allows you to hit test the DOM. The IE9 DOM interface also exposes a non-standard click function which invokes any click event handlers, this will cause an anchor element to navigate. Putting it together, if you have an anchor element at (x=100, y=100), you can cause it to navigate using the following simple code:

document.elementFromPoint(100, 100).click()

Calling this JavaScript from our native C# code in response to Tap events is very easy. I have wrapped it up into a simple utility class:

/// <summary>
/// Captures mouse left button up events, triggering an immediate
/// click event on the clicked DOM element.
/// </summary>
public class BrowserFastClick
{
  private WebBrowser _browser;
 
  private Border _border;
 
  public BrowserFastClick(WebBrowser browser)
  {
    _browser = browser;
    browser.Loaded += new RoutedEventHandler(Browser_Loaded);
  }
 
  private void Browser_Loaded(object sender, RoutedEventArgs e)
  {
    // locate the element used to capture mouse events
    _border = _browser.Descendants<Border>().Last() as Border;
    _border.Tap += Border_Tap;
  }
 
  private void Border_Tap(object sender, GestureEventArgs e)
  {
    //determine the click location
    var pos = e.GetPosition(_border);
 
    // forward to the browser
    _browser.InvokeScript("eval",
      string.Format("document.elementFromPoint({0},{1}).click()", pos.X, pos.Y));      
  }
}

To use it within a PhoneGap application, simply create an instance as follows:

new BrowserFastClick(PGView.Browser);

The net result is that your application becomes more responsive, with the browser immediately navigating links when they are first tapped.

I have updated the HTML5 SandwichFlow application I blogged about a few weeks ago to use this FastClick code. You can download the complete example here: HTML5SandwichFlow.zip

Regards, Colin E.

A Festive and Fun Windows Phone 7 Maze Game

December 22nd, 2011

Last night, with my Christmas presents all wrapped and a lack of any decent programmes (festive or otherwise) on television, I had a few hours to kill, so decided to create a festive-themed WP7 game …

Ever since I first started writing code for Windows Phone 7 I have wanted to do something involving physics and the accelerometer. I finally found a few hours to spare to give it a go. This blog post doesn’t go into too much detail about Farseer, the Physics Engine that I used, I didn’t really have time to learn it in any great detail. This post is more about how quickly you can put together something really quite cool in quite a short space of time using libraries and code grabbed from the internet.

The simple app I created renders a maze that you ‘roll’ a small ball around by tilting your phone:

This works well in the new 7.1 emulator where you can tilt the emulator via the extended controls. However, it works best on a real device, where you can control tilt far more easily. See the video below:

Farseer Physics Engine

The game makes use of the popular Farseer Physics Engine. This library allows you to create a world populated with physics bodies, supporting features such as friction, joints, motors and much much more. As I am a Silverlight developer I made use of the Physics Helper library which allows you to use the Farseer engine within a Silvelight application with very little effort. With the Physics Helper you simply make the Physics Engine ‘aware’ of the objects you wish it to control and it does the rest, animating them as they are subjected to gravity and other interactions.

The simplest way to use Physics Helper is via behaviours, this allows you to create a fully functioning ‘world’ without writing a single line of C# code. For example, you can create a ball and a surface that it will fall towards, eventually coming to rest, with just a few lines of XAML:

<Canvas x:Name="canvas">
  <!-- create our 'world' -->
  <i:Interaction.Behaviors>
    <pb:PhysicsControllerBehavior/>
  </i:Interaction.Behaviors>
 
  <Ellipse Width="100" Height="100" Fill="Red"
            Canvas.Left="80" Canvas.Top="100">
    <!-- make the engine aware of this element -->
    <i:Interaction.Behaviors>
      <pb:PhysicsObjectBehavior />
    </i:Interaction.Behaviors>
  </Ellipse>
 
 
  <Rectangle Width="500" Height="10" Fill="Blue"
              Canvas.Top="500">
    <!-- make the engine aware of this STATIC element -->
    <i:Interaction.Behaviors>
      <pb:PhysicsObjectBehavior IsStatic="True"/>
    </i:Interaction.Behaviors>
  </Rectangle>
</Canvas>

I find this pretty amazing!

Physics Helper will do much more, it can handle complex paths and geometries, explosions and collisions with minimal effort. For a greater insight into just how much is possible, I would recommend Andy Beaulieu’s Channel 9 article. Andy is the creator of Farseer, so really knows his stuff!

My maze is generated in C# code, so despite the elegance of using Physics Helper via behaviours, I need to add elements to my canvas programmatically. This means that I have to make the physics engine aware of their existence in code also. To achieve this, I add the behaviour in code as follows:

/// <summary>
/// Uses Physics Helper to create a physics body for the given element
/// </summary>
private void AddPhysicsBody(FrameworkElement element, bool isStatic)
{
  var behaviorCollection = Interaction.GetBehaviors(element);
  behaviorCollection.Add(new PhysicsObjectBehavior()
  {
    IsStatic = isStatic
  });
 
  var physicsObject = element.GetValue(PhysicsObjectMain.PhysicsObjectProperty) as PhysicsObjectMain;
  _physicsController.AddPhysicsBody(physicsObject);
}

Creating a Maze

I found numerous C# maze algorithms on the internet, most of them based on the same random-walk concept. There is a great description of this approach, with animated examples on this blog. Unfortunately every C# implementation I came across was tightly coupled to a specific UI framework, often WinForms or XNA (tut-tut remember to separate your concerns!). So, I took a simple maze algorithm from a software forum and ripped-out the WinForms / GDI rendering code. A new maze is constructed simply by creating an instance of the Maze class, passing it the number of rows and columns.

In order to render the maze using Silverlight elements, I simply took the original maze graphics code:

private void CreateMaze()
{
  // compute the number of rows / cols
  double ratio = mazeContainer.ActualHeight / mazeContainer.ActualWidth;
  int cols = _mazeSize;
  int rows = (int)((double)cols * ratio);
  double cellWidth = mazeContainer.ActualWidth / cols;
 
  // create the maze
  Maze maze = new Maze(rows, cols);
 
  // render the maze
  for (int i = 0; i < cols; ++i)
  {
    for (int j = 0; j < rows; ++j)
    {
      var room = maze.cells[i, j];
      if ((room & Maze.UP) != 0)
        DrawLine(i * cellWidth + cellWidth / 2,
                j * cellWidth,
                i * cellWidth + cellWidth / 2,
                j * cellWidth + cellWidth / 2 - 1);
      if ((room & Maze.DOWN) != 0)
        DrawLine(i * cellWidth + cellWidth / 2,
              j * cellWidth + cellWidth / 2,
              i * cellWidth + cellWidth / 2,
              j * cellWidth + cellWidth - 1);
      if ((room & Maze.RIGHT) != 0)
        DrawLine(i * cellWidth + cellWidth / 2,
              j * cellWidth + cellWidth / 2,
              i * cellWidth + cellWidth - 1,
              j * cellWidth + cellWidth / 2);
      if ((room & Maze.LEFT) != 0)
        DrawLine(i * cellWidth,
              j * cellWidth + cellWidth / 2,
              i * cellWidth + cellWidth / 2 - 1,
              j * cellWidth + cellWidth / 2);
    }
  }
}

And created a method that mimics the behaviour of the System.Drawing.Graphics.DrawLine method which the original maze code depended on:

private void DrawLine(double x1, double y1, double x2, double y2)
{
  double width = x2 - x1 + 2.0;
  if (width == 0.0) width = 2.0;
 
  double height =  y2 - y1+ 2.0;
  if (height == 0.0) height = 2.0;
 
  var rec = new System.Windows.Shapes.Rectangle()
  {
    Fill = new SolidColorBrush(Colors.Red),
    Width = width,
    Height = height
  };
  Canvas.SetLeft(rec, x1);
  Canvas.SetTop(rec, y1);
  mazeContainer.Children.Add(rec);
 
  AddPhysicsBody(rec, true);
}

A bit messy, but gets the job done!

The above code creates a maze comprised of static physics objects, where the _mazeSize field dictates the scale of the maze:

Adding a Rolling Ball

Adding a ball to the maze is simply a matter of creating an ellipse and adding it at the maze entrance. Note, this physics-body is not static, so will move under the influence of gravity:

Ellipse ball = new Ellipse()
{
  Width = cellWidth * 0.7,
  Height = cellWidth * 0.7,
  Fill = this.Resources["brush"] as Brush
};
Canvas.SetLeft(ball, ((cols / 2) + 0.7) * cellWidth);
Canvas.SetTop(ball, 0);
mazeContainer.Children.Add(ball);
 
AddPhysicsBody(ball, false);

By default, the ‘world’ has gravity with a fixed Y component and no X component. This causes all non-static bodies to fall downwards as you might expect. In order to guide the ball around the maze by tilting the phone, we need to adjust gravity based on accelerometer readings. This is achieved by the following code:

private void HandleAccelerometer()
{
  _sensor = new Accelerometer();
  _sensor.Start();
 
  // 10 times a second, update the gravity
  var gtimer = new DispatcherTimer();
  gtimer.Interval = TimeSpan.FromSeconds(0.1);
  gtimer.Tick += (s, e) =>
  {
    if (_physicsController.Simulator != null)
    {
      _physicsController.Simulator.Gravity.Y = 5 * -_sensor.CurrentValue.Acceleration.Y;
      _physicsController.Simulator.Gravity.X = 5 * _sensor.CurrentValue.Acceleration.X;
    }
  };
  gtimer.Start();
}

Note: this uses a timer, rather than updating the simulator every time the accelerometer reading changes. I found that without the timer, I was repeatedly seeing the generic “Element is already a child of another element” exception. You will also notice in the code that the maze is built after a pause of a couple of seconds, again in order to avoid this issue. There’s something funny going on inside the Physics Helper!

Finally, we handle collisions in order to play a simple sounds effect a the ball bounces off each wall:

// locate the physics controller
_physicsController = mazeContainer.GetValue(PhysicsControllerMain.PhysicsControllerProperty) as PhysicsControllerMain;
 
// load the WAV file
Stream stream = TitleContainer.OpenStream("boing1.wav");
_effect = SoundEffect.FromStream(stream);
FrameworkDispatcher.Update();
 
// play on each collision
_physicsController.Collision += (s,e) => _effect.Play();

And there we have it, a simple maze game powered by the Farseer Physics engine. The whole thing only took about an hour to create, with code grabbed from the internet – a bit rough and ready, but I was impressed with how easy it was to create this game. There is much more that could be done, for example detecting when the ball reaches the end of the maze, advancing to a more difficult level, however, my time has run out on this bit of fun … Also, if I were to take this idea further, I would probably use XNA rather than Silverlight. The Physics Helper is great for simple XAML-only physics models, but I feel that it wasn’t really built for programmatic creation of bodies.

You can download the code here: WP7MazeGame.zip

Note, you will have to download and install Physics Helper to run this code.

On another note, Farseer is clearly the result of hundreds of hours of development effort, which makes it easy to create realistic physics-based applications and games. Farseer is free to use under the MS-PL licence. However, I would urge anyone who has used this great library to create a WP7 game to donate via the Farseer codeplex site (scroll to the bottom).

Regards, Colin E.

A Simple Multi-Page Windows Phone 7 PhoneGap Example

December 15th, 2011

This blog post shows how you can use PhoneGap to create Windows Phone 7 applications that are comprised of multiple, simple HTML pages, whilst meeting the Marketplace certification requirements.


Colin Eberhardt is a Scott Logic technical Evangelist and a Technical Architect for Visiblox, suppliers of high-performance WPF and Silverlight charts.

Readers of my blog will know that I have been working on, and writing about, the use of PhoneGap to create HTML5-based Windows Phone 7 applications. Along the way I have solved problems such as back-button support, tombstoning and suppressing browser pan and zoom. So far the applications I have discussed have all been single-page JavaScript applications, i.e. the WebBrowser control loads a single HTML page which links to the application JavaScript. All subsequent navigation involves updating the DOM dynamically rather than navigating to a new URL. However, I have had numerous questions to my previous blog posts from people who are using PhoneGap to create simple navigation-based applications. In this context PhoneGap is being used as a mechanism for packaging up a collection of relatively static HTML pages.

So why would you want to do this? This is a perfectly valid question! If you have static HTML based content why not simply put it on the web? There are a few reasons, one is to ensure that the content is always available, whether the phone is connected to a network or not. Another is monetization, the app-store model provides an easy way to charge for this content. Regardless of the pros and cons, based on the feedback my previous articles have received, people are very interested in using PhoneGap as a model for packaging static content.

In this blog post I will show how to solve the problems of back-button support and pan / zoom for a simple navigation-based HTML application. As an example, I have chosen a subject which I have a lot of interest in … sandwiches! I have previously blogged about SandwichFlow, an example application which showcased my metro-in-motion series, here I have transformed the sandwich recipe HTML into a collection of static HTML pages.

Packaging the HTML

My first PhoneGap blog post detailed how to get up-and-running with PhoneGap, if you have never used this framework before I would recommend that you read that first. Packaging my sandwich recipe content into an application was simply a matter of copying the files (HTML and CSS) into the ‘www’ directory, running the T4 template that auto-generates the GapSourceDictionary.xml, building and running. The resulting application is as follows:

PhoneGap does a great job of making it very easy to package HTML content into an application, loading the files into isolates storage etc … However, there are a few Windows Phone 7 specific concepts that have to be supported in order to ensure certification on submission to the marketplace.

Back-button Support

UPDATE: There are a few issues with the code below. See my more recent blogpost for an improved solution.

Correct back-button support is a mandatory requirement for marketplace certification. Hitting the back button should navigate back through the various screens of an application. Hitting the back-button on the first screen should terminate the application. The standard PhoneGap Visual Studio template does not support the back-button by default, this no-doubt reflects the fact that the other PhoneGap platforms (iPhone, Android, BlackBerry) do not share this same requirement, or lack a back-button altogether.

In my previous blog post on back-button support I described how a single-page JavaScript application can manage its own back-stack. This approach does not work for navingation-based HTML applications.

The WebBrowser control which PhoneGap uses to render its contents stores its navigation history in the same way that a desktop browser does. This history can be accessed via the JavaScript ‘history’ object. If the back-button is pressed after navigating to one of the packaged HTML pages, invoking history.go(-1) will cause the WebBrowser control to navigate backwards. All we need to do is to keep track of navigation events to determine whether to route the back-button too our HTML application or not.

The following utility class does just that:

/// <summary>
/// Handles the back-button for a PhoneGap application. When the back-button
/// is pressed, the browser history is navigated. If no history is present,
/// the application will exit.
/// </summary>
public class BackButtonHandler
{
  private int _browserHistoryLength = 0;
  private PGView _phoneGapView;
 
  public BackButtonHandler(PhoneApplicationPage page, PGView phoneGapView)
  {
    // subscribe to the hardware back-button
    page.BackKeyPress += Page_BackKeyPress;
 
    // handle navigation events
    phoneGapView.Browser.Navigated += Browser_Navigated;
 
    _phoneGapView = phoneGapView;
  }
 
  private void Browser_Navigated(object sender, NavigationEventArgs e)
  {
    if (e.NavigationMode == NavigationMode.New)
    {
      _browserHistoryLength++;
    }
  }
 
  private void Page_BackKeyPress(object sender, CancelEventArgs e)
  {
    if (_browserHistoryLength > 1)
    {
      _phoneGapView.Browser.InvokeScript("eval", "history.go(-1)");
      _browserHistoryLength -= 2;
      e.Cancel = true;
    }
  }
}

Note: I have had a number of requests from readers who do not have any C# / Silverlight experience, so are unsure how to use code snippets like the one above. In this blog post I have included the full sourcecode. Just grab the code and replace the contents of the ‘www’ directory with your own content, and you are good to go!

With the above code in place the application now supports the back-button

With this feature in place you should be able to successfully submit a PhoneGap based application to the Windows Phone 7 marketplace. The other bits of code that follow are all about improving the cosmetics.

Suppressing Pan and Zoom

Whilst the viewport metadata settings can be used to prevent scaling, the cosmetics of this feature are not terribly good with Windows Phone 7, the user can still ‘pinch’ your HTML page, however, it snaps back to its original scale when the manipulation ends. I previously published a simple class which can intercept manipulation events in order to suppress the pinch zoom behaviour.

This class can also ‘lock’ the browser windows entirely, supressing scroll as well as zoom. However, this is only appropriate for use on pages where you can be sure the content fits entirely within a single page. In order to ‘activate’ this behaviour we need to send a message from the HTML / JavaScript to the C# utility class. The ’about’ page of this application does just that. When it is loaded the following JavaScript is executed:

<script type="text/javascript" charset="utf-8">
  // ensure that this page does not scroll
  window.external.Notify("noScroll");
</script>

The utility class (described in the earlier blog post) is instantiated in code-behind, with the above Notify being used to ‘lock’ the page:

private WebBrowserHelper _browserHelper;
 
// Constructor
public MainPage()
{
  InitializeComponent();
 
  new BackButtonHandler(this, PGView);
  _browserHelper = new WebBrowserHelper(PGView.Browser);
 
  PGView.Browser.ScriptNotify += Browser_ScriptNotify;
  PGView.Browser.Navigated += Browser_Navigated;
}
 
private void Browser_Navigated(object sender, NavigationEventArgs e)
{
  // when we first navigate to a page, we assume that it can be scrolled
  _browserHelper.ScrollDisabled = false;
}
 
private void Browser_ScriptNotify(object sender, NotifyEventArgs e)
{
  // if a page notifies that it should not be scrollable, disable
  // scrolling.
  if (e.Value == "noScroll")
  {
    _browserHelper.ScrollDisabled = true;
  }
}

Again, the code above is included in the download at the end of this article. To ‘lock’ the scroll on any of your HTML pages, simply add the JavaScript ‘Notify’ above.

Splashscreen

One final cosmetic issue is the application startup. The application splashcreen is hidden automatically when your application starts up. This is fine for a native application, however a PhoneGap application isn’t quite ready at this point. After the native wrapper starts, the code is loaded into the WebBrwoser control and the HTML / JavaScript application starts. This results in a rather ugly white screen appearing for ~ 0.5 second when the application starts up.

The start screen duration is not configurable, however, there is a simple solution to this problem, when the application first starts, render the splashscreen as the application content, then hide this image when the PhoneGap application starts.

To do this, create an image and position it in front of the PhoneGap browser control:

<Grid x:Name="LayoutRoot" Background="Transparent">
 
  <my:PGView HorizontalAlignment="Stretch" 
                  Margin="0,0,0,0"  
                  Name="PGView" 
                  VerticalAlignment="Stretch"/>
 
  <Image Source="/SplashScreenImage.jpg"
          x:Name="splashImage">
    <Image.Resources>
      <Storyboard x:Name="fadeOut"
                  BeginTime="0:0:0.5"
                  Completed="fadeOut_Completed">
        <DoubleAnimation
                Storyboard.TargetName="splashImage"
                Storyboard.TargetProperty="Opacity"
                From="1.0" To="0.0" Duration="0:0:0.3"/>
      </Storyboard>
    </Image.Resources>
  </Image>
</Grid>

This image has a storyboard that fades-out the image.

This animation is triggered when the browser navigates to the first age of the application:

EventHandler<NavigationEventArgs> hideSplashScreen = null;
hideSplashScreen = (s, e ) =>
  {
    fadeOut.Begin();
    PGView.Browser.Navigated -= hideSplashScreen;
  };
PGView.Browser.Navigated += hideSplashScreen;

Finally, the Completed event handler removes the image altogether when the animation ends:

private void fadeOut_Completed(object sender, EventArgs e)
{
  splashImage.Visibility = Visibility.Collapsed;
}

Conclusions

Hopefully this blog post will help people who are new to WP7 and wish to release PhoneGap applications comprised of multiple HTML pages.

You can download the sourcecode: HTML5SandwichFlow.zip

Regards, Colin E.

A Windows Phone 7 Slide View with Page Pips

December 8th, 2011

A popular user-interface in the iOS world is the UIPageControl which renders a small set of dots to indicate the number of pages, with the current page highlighted in some way. This is often used in conjunction with a UIScrollView to navigate between pages in a multi-page layout.

Windows Phone 7 has a Pivot control which allows you to swipe in order to navigate content across multiple screens. However, the Pivot control is most often used when each ‘page’ has some logic header – in some ways it is analogous to a desktop tab control. I decided to use this control, without specifying headers for each PivotItem, then add my own control to render the ‘pips’.

The control that displays the location pips is defined in XAML, with the relationship between this control and the Pivot created via an ElementName binding:

<local:PivotLocationView Source="{Binding ElementName=pivot}"
                          HorizontalAlignment="Center"
                          VerticalAlignment="Bottom"
                          Margin="0,0,0,10"/>
 
<controls:Pivot Margin="0,-30,0,40" 
                x:Name="pivot">
  <controls:PivotItem>
    ...
  </controls:PivotItem>
  <controls:PivotItem>
    ...
  </controls:PivotItem>
  <controls:PivotItem>
    ...
  </controls:PivotItem>
</controls:Pivot>

Note the negative top margin for the Pivot, this control still allocates some header space, even when no headers are defined.

The PivotLocationView user control is backed by a simple view model, with model-items for each pip. When the view model is associated with a Pivot control, it creates a child view model for each Pivot Item, then handles the SelectionChanged event in order to keep the selection state synchronized:

public class PivotLocationViewModel
{
  private Pivot _pivot;
 
  public PivotLocationViewModel()
  {
  }
 
  public PivotLocationViewModel(Pivot pivot)
  {
    PivotItems = new PivotItemViewModelCollection();
    SetPivot(pivot);
  }
 
  /// <summary>
  /// Gets or sets the collection of child view-models
  /// </summary>
  public PivotItemViewModelCollection PivotItems { get; set; }
 
  private void SetPivot(Pivot pivot)
  {
    _pivot = pivot;
 
    // handle selection changed
    pivot.SelectionChanged += Pivot_SelectionChanged;
 
    // create a view model for each pivot item.
    for(int i=0;i<pivot.Items.Count;i++)
    {
      PivotItems.Add(new PivotItemViewModel());
    }
 
    // set the initial selection
    PivotItems[_pivot.SelectedIndex].IsSelected = true;
  }
 
  /// <summary>
  /// Handle selection changes to update the view model
  /// </summary>
  private void  Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
  {
 	  var selectedModel = PivotItems.SingleOrDefault(p => p.IsSelected);
    if (selectedModel != null)
      selectedModel.IsSelected = false;
 
    PivotItems[_pivot.SelectedIndex].IsSelected = true;
  }
 
}

The view model for each pivot item is a simple model that implements INotifyPropertyChanged. It has an IsSelected property that reflects the selection state of the Pivot, it also exposes a Color property that indicates the color for each ‘pip’. This could have been implemented as a value converter, but there is little point as we already have a view model:

/// <summary>
/// A view model for each 'pip'
/// </summary>
public class PivotItemViewModel : INotifyPropertyChanged
{
  // ... INotifyPropertyChanged implementation
 
  private bool _isSelected;
 
  public bool IsSelected
  {
    get { return _isSelected; }
    set
    {
      if (_isSelected == value)
        return;
 
      _isSelected = value;
      OnPropertyChanged("IsSelected");
 
      Color = IsSelected ? Colors.Black : Colors.White;
    }
  }
 
  private Color _color;
 
  public Color Color
  {
    get { return _color; }
    set
    {
      _color = value;
      OnPropertyChanged("Color");
    }
  }
}

The XAML for this control is very simple, using an ItemsControl to render an ellipse for each ‘pip’:

<UserControl ...
    d:DataContext="{d:DesignData Source=PivotLocationViewModel.xml}">
 
  <Grid x:Name="LayoutRoot">
    <ItemsControl ItemsSource="{Binding PivotItems}">
      <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
          <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
      </ItemsControl.ItemsPanel>
      <ItemsControl.ItemTemplate>
        <DataTemplate>
          <Ellipse Width="12" Height="12" Margin="15,0,15,0"
                   Stroke="Black"
                   StrokeThickness="0.5">
            <Ellipse.Fill>
              <SolidColorBrush Color="{Binding Color}"/>
            </Ellipse.Fill>
          </Ellipse>
        </DataTemplate>
      </ItemsControl.ItemTemplate>
    </ItemsControl>
  </Grid>
</UserControl>

Note, the use of design-time data. The following file defines a view model instance:

<PivotLocationViewModel xmlns="clr-namespace:SlideView">
  <PivotLocationViewModel.PivotItems>
    <PivotItemViewModelCollection>
      <PivotItemViewModel IsSelected="False" Color="Red"/>
      <PivotItemViewModel IsSelected="True"  Color="Green"/>
      <PivotItemViewModel IsSelected="False"  Color="Red"/>
      <PivotItemViewModel IsSelected="False"  Color="Red"/>
    </PivotItemViewModelCollection>
  </PivotLocationViewModel.PivotItems>
</PivotLocationViewModel>

This makes creating the above user control much easier, because it can be visualised in the designer:

And there you have it, a simple user-control, which when used in conjunction with a Pivot, provides an interface where the user can swipe between pages.

You can download the full sourcecode: SlideView.zip

Regards, Colin E.