Colin Eberhardt's Technology Adventures

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 Metro Themed PowerPoint Template

December 19th, 2011

Over the weekend I mentioned on Twitter that I had created a Metro-style PowerPoint template. There were a few requests to share, so hence this blog post. Scroll to the bottom to download the PowerPoint file.

So why create a Metro-style PowerPoint presentation? A couple of reasons, firstly, the templates that come with PowerPoint are absolutely awful!

They look very dated (to put it politely). Secondly, with the Metro Design Language, which was introduced with Windows Phone 7, Microsoft have come up with something surprisingly stylish. Metro is about clarity, readability, simplicity – concepts that map very well to presentations.

The ‘classic’ Metro look, which I have tried to re-produce with this template, includes highly legible san-serif fonts (from the Segoe family), a lack of chrome (i.e. shadows, gradient) and fluid motions. Many metro applications do include background imagery to add ‘warmth’, as I have done here also.

I have created a template with a master and a number of layouts. Each layout includes a number of sequenced animations, mimicking the ‘fast and fluid’ Metro interface:

PowerPoint can be used to create some rather neat sequenced animations, if you ignore the rather garish defaults.

To get a better feel for this template, have a look at it in motion (the quality here is rather poor, I haven’t managed to find a screen capture tool that works well for subtle colours):

If you want to use this template, you might want to change the background image. You can do this via the ‘slide master view’. The background I included is one I found on the free stock imagery site stock.xcnhg, by the user fangol. There are numerous other free images on that site. Please remember to attribute your usage of free stock images.

You might also find that you need to add new layouts based on your content. Again, this is easy to do via the master view.

Anyhow, here is the template, enjoy: MetroStyle.pptx

NOTE: Until I get the mime-types sorted out you might have to right click and select “save as” to save the above PowerPoint file.

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.