Speaking at WiPhug: 3 times Windows Phone 7

Today, the Wiphug (Windows Phone User Group Belgium) held their 3rd event.
This time it was in Kortenberg, in a big villa which houses the company Proximity BBDO.

Today we experimented with short talks about Windows Phone development.
So we had 3 speakers, of which I was one of them.
Everybody got a max of 40 minutes to cover a subject.
I like the format very much, because you get to see a lot of things, in a very short time, and from a lot of different people.
So no more feeling you wasted your time because you knew all about the subject or the speaker sucked in your opinion [not that we ever would invite sucking speakers, but tastes do differ] – anyway that “torture” (if you will) will only last for max 40 minutes – not that bad, huh.
Above all that it gives the WiPhug the opportunity to have more speakers, so maybe you feel like you need to share a subject ?
If you feel the need to share, please contact board@wiphug.be and we’ll arrange something.

My talk was about how to play sounds and it’s certification requirements, I choose this topic because of an app I recently published called ‘SheepCounter‘. It was an attempt at writing an app without using code… unfortunatly this is a myth… you need to code several behaviours at least, which you then can implement by clicking your way through Blend. While failing at the attempt of doing a no code app, I did learn a lot about playing sounds, and it’s certification requirements.
And that’s what I wanted to share with you all.

It was a very pleasent evening – like all WiPhug get-to-gethers by the way, and the more we’re organising these events, the more we start to get to know our members/followers.

You can find my presentation and example code about “Playing sounds on Windows Phone” online.

Be sure to think about your next WiPhug presentation ! You’re always welcome to speak at one of our events !

Advertisements

Speaking at WiPhug: Building a Windows Phone application from Z to A

Today I spoke at the Windows Phone User Group Belgium – of which I’m a board member too – about the development of our WiPhug Windows Phone app.
Our first event was a success we had about 46 people comming from all over the country (mainly Flanders and Brussels though) to Mechelen… and if there were not that many traffic jams because of the bad weather it would have been more… I’m sure !
For me it was the very first time on stage.

Good preparation and Tekpub’s video featuring Scott Hanselmans entitled “The Art Of Speaking” gave me the necessary confidence for the 2 hour presentation.
My fellow boardmembers Glenn and Bart – who actually did most of the development of the app – I focussed more on the presentation and some design elements for the app – gave the demoes… and frankly I thaught they did a great job… for all of us it was a first time on stage, so we could have done worse I guess.

Be sure to check out the blogpost I wrote on the WiPhug site about the event, it tells a bit more in detail how the evening went along.

I have to admit that the kick you get from presenting is AWESOME, I can only advise people to try to speak in front of an audience, especially if they are still hesitating, if you know the subject you’re about to speak well, then there’s no need to hesitate.

This tastes for more !

How to create a TimePicker that goes by 15 minute increments ?

For a new app that I’m writing I needed a TimePicker that did not show every minute in the TimePicker.
I wanted to give the user a TimePicker where the user can select the time in increments of 15 minutes, so 0 minutes, 15 minutes, 30 minutes and 45 minutes past the hour.
Unfortunately the TimePicker that we find in the Silverlight Toolkit for Windows Phone doesn’t have a property “Step” or “Increment”, so you have to create that yourself.

Luckily the guys at Windows Phone Geek have a nice and clear explanation on all the ingredients to get there. You can either continue reading here, or you can first read the “WP7 DatePicker and TimePicker in depth” article and then at least the first 2 parts of the 3-part “WP7 LoopingSelector in depth” article.

To make a long story short: because there is no “Step” or “Increment” property on the TimePicker, we have to create a custom PickerPage, that contains several LoopingSelector to imitate the looks and behaviour of the TimePicker, as you know it when you set an alarm for example.
The Windows Phone Geek article about the TimePicker shows you how to link a custom PickerPage to your TimePicker, and the LoopingSelector article tells us how create a LoopingSelector for whatever type we feed it and how to style LoopingSelector.

Let’s start with the beginning, on your page – where you want to use the TimePicker with Custom PickerPage – add the TimePicker object. Make sure you make the box long enough, especially if you are in a country that doesn’t use “AM” and “PM” in their times. If your app will be used in the US or UK, this crucial piece of information might “fall out” of your box, and the user will not know when exactly is meant.

TimePicker HorizontalAlignment="Left"
           Margin="136,6,0,0"
           Name="timePicker1"
           VerticalAlignment="Top"
           Width="180" />

Now add a new Windows Phone Page to the project, I called mine “TimePickerPage.xaml” but you can call it whatever you want of course.
Then add the name of the newly added page in the PickerPageUri property of the TimePicker.

TimePicker HorrizontalAlignment="Left"
           Margin="136,6,0,0"
           Name="timePicker1"
           VerticalAlignment="Top"
           Width="180"
           PickerPageUri="/TimePickerPage.xaml" />

Now open the code behind of the TimePickerPage.xaml, and add the IDateTimePickerPage interface, so that inherits not only from the PhoneApplicationPage, but that it also implements the IDateTimePickerPage interface. The IDateTimePickerPage can be found in the Microsoft.Phone.Controls.Primitives assembly.

using Microsoft.Phone.Controls.Primitives;

public partial class TimePickerPage : PhoneApplicationPage, IDateTimePickerPage
{
    ...
}

If you implement the IDateTimePickerPage interface you will receive a “DateTime? Value” property which you need, to communicate back the selected time to the TimePicker Control. You can remove the “throw new NotImplementedException();“, since we don’t want exceptions to be thrown of course.

public DateTime? Value
{
    get;
    set;
}

If you like you can test this now, but you won’t see much yet, important is that you’ll notice that your new page gets loaded when you tap on the TimePicker… unfortunately then you’re stuck, but we’ll be working on that right now.
To avoid being stuck on our TimePickerPage, let’s add an ApplicationBar and implement the cancel button.
Uncomment the default ApplicationBar, remove the menu, but keep 2 buttons. Make sure that the images of your buttons have their Build Action property set to Content, which you probably already have done since you use the Silverlight Toolkit for Windows Phone for all this.

<phone:PhoneApplicationPage.ApplicationBar>
	<shell:ApplicationBar IsVisible="True" IsMenuEnabled="False">
		<shell:ApplicationBarIconButton IconUri="/Toolkit.Content/ApplicationBar.Check.png" Text="done" />
		<shell:ApplicationBarIconButton IconUri="/Toolkit.Content/ApplicationBar.Cancel.png" Text="cancel" Click="ApplicationBarCancelButton_Click" />
	</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>

The code behind for the cancel button is very simple, it looks like this:

private void ApplicationBarCancelButton_Click(object sender, EventArgs e)
{
	NavigationService.GoBack();
}

If you run now, you can return back to the MainPage after tapping on the cancel button.

Now let’s focus on imitating the default TimePickerPage. First let us look at the originals to remember us what we’ll need to create.

Below you’ll see how the 24-hour TimePicker looks like.

Our US and UK friends, who use a 12-hour system with AM and PM to mark Ante Meridiem – before midday – and Post Meridiem – after midday, the TimePicker looks like this.

If your app can possibly attract an international public we need to support both the 24-hour and the 12-hour clocks. There’s an option in the Settings of your phone which allows you to choose a “24-hour clock”, unfortunatly as a developer you can’t retrieve this setting, so to give your users a more or less OK experience which almost goes quite the way, but not completely, you need to check what is the format of a ToShortTimeString(). Very sad that Microsoft forgot about a way to retrieve the “24-hour clock” setting.
It’s not quite that, because an American can use the 24-hour setting, but the ToShortTimeString() will nontheless return something like “4:45:21 PM” instead of “16:45:21”, very strange behaviour ?!

Let’s analyse what exactly we need to recreate this user experience, depending on 12-hour or 24-hour settings, we need 3 (for 12-hours) or 2 (for 24-hours) LoopingSelectors – that’s how these scrollers that contain the numbers for the hours and minutes are called. You can find these LoopingSelectors in the Microsoft.Phone.Controls.Primitives namespace of the Microsoft.Phone.Controls.Toolkit assembly.
So, open your TimePickerPage.xaml file again, and add the Microsoft.Phone.Controls.Primitives XMLNamespace, so we can use the control on our custom PickerPage.

<phone:PhoneApplicationPage ... bunch of already referenced xmlns' ...
                            ... below those, add this ...
                            xmlns:toolkitPrimitives="clr-namespace:Microsoft.Phone.Controls.Primitives;assembly=Microsoft.Phone.Controls.Toolkit"
                            ... more Page directives ...
                            shell:SystemTray.IsVisible="True">

As we can see in the examples the SystemTray (the upper part of the phone’s screen that shows the time and connectivity) is visible, so leave that as is.
The first thing we notice is that there is only 1 title, the small one – called ApplicationTitle, so change the “MY APPLICTION” into “SELECT TIME”. Since there is only one title, you can remove the TextBlock which is named “PageTitle”.
Your TitlePanel should look like this now.

<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
    <TextBlock x:Name="ApplicationTitle" Text="SELECT TIME" Style="{StaticResource PhoneTextNormalStyle}"/>
</StackPanel>

No big deal so far, even the next part is not so exiting, in short you’ll be adding a StackPanel that contains 3 LoopingSelectors – one for hours, one for minutes and one for AM/PM, this last one we’ll collapse or make visible depending on the time settings – to the ContentPanel.

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
	<StackPanel Margin="0" Orientation="Horizontal"  HorizontalAlignment="Center">
		<toolkitPrimitives:LoopingSelector x:Name="HoursLoopingSelector" Margin="0,0,6,0" ItemMargin="0,6,0,6" ItemSize="136,148" Width="136" Height="606"/>
		<toolkitPrimitives:LoopingSelector x:Name="MinutesLoopingSelector" Margin="6,0,6,0" ItemMargin="0,6,0,6" ItemSize="136,148" Width="136" Height="606" />
		<toolkitPrimitives:LoopingSelector x:Name="AMPMLoopingSelector" Margin="6,0,0,0" ItemMargin="0,6,0,6" ItemSize="136,148" Width="136" Height="404" Visibility="Collapsed" />
	</StackPanel>
</Grid>

Important to remember, when you use the LoopingSelectors, is to set their Height-property big enough, else you won’t see anything, because the Height property is used when displaying the other items – I mean the Height doesn’t only count for the tile, but for the whole scrolling thing too.
You use the ItemSize property to define how big the items themselfs are. Also the height in the ItemSize (2nd parameter) should include the space you want to add between the scrollable items (magic number here – as in all Windows Phone design – is 12 pixels).
To recreate the exact same experience you still need to template the LoopingSelectors. Below you see how to make it all look very much like the real thing.

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
	<StackPanel Margin="0" Orientation="Horizontal"  HorizontalAlignment="Center">
		<toolkitPrimitives:LoopingSelector x:Name="HoursLoopingSelector" Margin="0,0,6,0" ItemMargin="0,6,0,6" ItemSize="136,148" Width="136" Height="606">
			<toolkitPrimitives:LoopingSelector.ItemTemplate>
				<DataTemplate>
					<Grid>
						<TextBlock Text="{Binding}" HorizontalAlignment="Left" VerticalAlignment="Bottom" FontSize="56" Margin="8,0,0,0" />
					</Grid>
				</DataTemplate>
			</toolkitPrimitives:LoopingSelector.ItemTemplate>
		</toolkitPrimitives:LoopingSelector>
		<toolkitPrimitives:LoopingSelector x:Name="MinutesLoopingSelector" Margin="6,0,6,0" ItemMargin="0,6,0,6" ItemSize="136,148" Width="136" Height="606">
			<toolkitPrimitives:LoopingSelector.ItemTemplate>
				<DataTemplate>
					<Grid>
						<TextBlock Text="{Binding}" HorizontalAlignment="Left" VerticalAlignment="Bottom" FontSize="56" Margin="8,0,0,0" />
					</Grid>
				</DataTemplate>
			</toolkitPrimitives:LoopingSelector.ItemTemplate>
		</toolkitPrimitives:LoopingSelector>
		<toolkitPrimitives:LoopingSelector x:Name="AMPMLoopingSelector" Margin="6,0,0,0" ItemMargin="0,6,0,6" ItemSize="136,148" Width="136" Height="404" Visibility="Collapsed">
			<toolkitPrimitives:LoopingSelector.ItemTemplate>
				<DataTemplate>
					<Grid>
						<TextBlock Text="{Binding}" HorizontalAlignment="Left" VerticalAlignment="Bottom" FontSize="56" Margin="8,0,0,0" />
					</Grid>
				</DataTemplate>
			</toolkitPrimitives:LoopingSelector.ItemTemplate>
		</toolkitPrimitives:LoopingSelector>
	</StackPanel>
</Grid>

Important to remember is that the numbers on the tiles (items) are on the bottom left, and they don’t “stick” to the side as we can see it the examples above (they are about 12 pixels from the border, this is achieved with a margin of 8, because the font itself has a little margin too), also the font is 40px in height, which is achieved with a FontSize of 56.
If you run the app now you see much now either. So let’s do something about that.

When you read the 2nd part of the WP7 LoopingSelector in depth you’ll learn how to create a generic LoopingSelectorDataSource.
We need a ListLoopingDataSource because if you watch closely to the examples you see that the minutes selector uses “00” for 0 minutes after the hour. So you will have an int for the hour selector (0 to 24 or 1 to 12), and a string for the minutes (“00”, “15”, “30”, “45” because we wanted to give the user a per 15 minutes experience). We will need to convert the minute string back to an int before passing this to various other methods, as you will see later.

First we’ll create an abstract base class of which we inherit later, this abstract base class will implement an interface called ILoopingSelectorDataSource.
In fact the ILoopingSelectorDataSource defines 2 methods : GetPrevious() and GetNext() to find the previous or next item in the collection; a property called SelectedItem and of course a SelectionChanged event to broadcast the change.
To get more details about this class I refer to original article at the WindowsPhoneGeek.com. If you don’t care about it, and just want to make it work, copy and paste this in a new class file or below your TimePickerPage class.

// abstract the reusable code in a base class
// this will allow us to concentrate on the specifics when implementing deriving looping data source classes
public abstract class LoopingDataSourceBase : ILoopingSelectorDataSource
{
	private object selectedItem;

	#region ILoopingSelectorDataSource Members

	public abstract object GetNext(object relativeTo);

	public abstract object GetPrevious(object relativeTo);

	public object SelectedItem
	{
		get
		{
			return this.selectedItem;
		}
		set
		{
			// this will use the Equals method if it is overridden for the data source item class
			if (!object.Equals(this.selectedItem, value))
			{
				// save the previously selected item so that we can use it 
				// to construct the event arguments for the SelectionChanged event
				object previousSelectedItem = this.selectedItem;
				this.selectedItem = value;
				// fire the SelectionChanged event
				this.OnSelectionChanged(previousSelectedItem, this.selectedItem);
			}
		}
	}

	public event EventHandler<SelectionChangedEventArgs> SelectionChanged;

	protected virtual void OnSelectionChanged(object oldSelectedItem, object newSelectedItem)
	{
		EventHandler<SelectionChangedEventArgs> handler = this.SelectionChanged;
		if (handler != null)
		{
			handler(this, new SelectionChangedEventArgs(new object[] { oldSelectedItem }, new object[] { newSelectedItem }));
		}
	}

	#endregion
}

So, now we still need the ListLoopingDataSource class that will inherit from our abstract class LoopingDataSourceBase.
In fact if you want to understand what exactly happens in this class, and why certain things are in this class I want to refer to the superb explanation in the original article at the WindowsPhoneGeek.com. If you don’t care about it, and just want to make it work, copy and paste this in a new class file or below your TimePickerPage class.

public class ListLoopingDataSource<T> : LoopingDataSourceBase
{
	private LinkedList<T> linkedList;
	private List<LinkedListNode<T>> sortedList;
	private NodeComparer nodeComparer;
	private IComparer<T> comparer;

	public ListLoopingDataSource() { }

	public IEnumerable<T> Items
	{
		get
		{
			return this.linkedList;
		}
		set
		{
			this.SetItemCollection(value);
		}
	}

	private void SetItemCollection(IEnumerable<T> collection)
	{
		this.linkedList = new LinkedList<T>(collection);
		this.sortedList = new List<LinkedListNode<T>>(this.linkedList.Count);
		
		// initialize the linked list with items from the collections
		LinkedListNode<T> currentNode = this.linkedList.First;
		while (currentNode != null)
		{
			this.sortedList.Add(currentNode);
			currentNode = currentNode.Next;
		}

		IComparer<T> comparer = this.comparer;
		if (comparer == null)
		{
			// if no comparer is set use the default one if available
			if (typeof(IComparable<T>).IsAssignableFrom(typeof(T)))
			{
				comparer = Comparer<T>.Default;
			}
			else
			{
				throw new InvalidOperationException("There is no default comparer for this type of item. You must set one.");
			}
		}

		this.nodeComparer = new NodeComparer(comparer);
		this.sortedList.Sort(this.nodeComparer);
	}

	public IComparer<T> Comparer
	{
		get
		{
			return this.comparer;
		}
		set
		{
			this.comparer = value;
		}
	}

	public override object GetNext(object relativeTo)
	{
		// find the index of the node using binary search in the sorted list
		int index = this.sortedList.BinarySearch(new LinkedListNode<T>((T)relativeTo), this.nodeComparer);
		if (index < 0)
		{
			return default(T);
		}

		// get the actual node from the linked list using the index
		LinkedListNode<T> node = this.sortedList[index].Next;
		if (node == null)
		{
			// if there is no next node get the first one
			node = this.linkedList.First;
		}
		return node.Value;
	}

	public override object GetPrevious(object relativeTo)
	{
		int index = this.sortedList.BinarySearch(new LinkedListNode<T>((T)relativeTo), this.nodeComparer);
		if (index < 0)
		{
			return default(T);
		}
		LinkedListNode<T> node = this.sortedList[index].Previous;
		if (node == null)
		{
			// if there is no previous node get the last one
			node = this.linkedList.Last;
		}
		return node.Value;
	}

	private class NodeComparer : IComparer<LinkedListNode<T>>
	{
		private IComparer<T> comparer;

		public NodeComparer(IComparer<T> comparer)
		{
			this.comparer = comparer;
		}

		#region IComparer<LinkedListNode<T>> Members

		public int Compare(LinkedListNode<T> x, LinkedListNode<T> y)
		{
			return this.comparer.Compare(x.Value, y.Value);
		}

		#endregion
	}
}

OK, now that we have all the ingredients in place, we only need to use these classes now, so finally we get some items in our selectors.
So, open the codebehind of your TimePickerPage again, and right below the “InitializeComponent();” you’ll be add some more code. Start with defining the 4 Lists which will be used to fill the LoopingSelectors.

List<int> hours24 = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };
List<int> hours12 = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
List<string> minutes = new List<string>() { "00", "15", "30", "45" };
List<string> ampm = new List<string>() { "AM", "PM" };

...

We can already fill the minutes and the AM/PM selectors, to do that, you’ll set the DataSource properties of the LoopingSelectors, like so:

...

this.MinutesLoopingSelector.DataSource = new ListLoopingDataSource<string>() { Items = minutes, SelectedItem = "00" };
this.AMPMLoopingSelector.DataSource = new ListLoopingDataSource<string>() { Items = ampm, SelectedItem = "AM" };

...

The HoursLoopingSelector is a little trickier, because we need to fill that one with either a 24 hour or a 12 hour list, depending on the user settings. But as I already told you, there’s no way to check if the user has set his clock to the “24 hour clock” mode in his settings or not. The closest thing to an OK experience is to check if the ShortTimePattern uses 24 hours or 12 hours (which mean that the pattern will use a “h” for 12 hours instead of “H” for 24 hours).
Also we need to make Visible or Collapse the AM/PM LoopingSelector depending on the ShortTimePattern.

...

if (DateTimeFormatInfo.CurrentInfo.ShortTimePattern.Contains("H"))
{
	this.HoursLoopingSelector.DataSource = new ListLoopingDataSource<int>() { Items = hours24, SelectedItem = 0 };
	this.AMPMLoopingSelector.Visibility = Visibility.Collapsed;
}
else
{
	this.HoursLoopingSelector.DataSource = new ListLoopingDataSource<int>() { Items = hours12, SelectedItem = 1 };
	this.AMPMLoopingSelector.Visibility = Visibility.Visible;
}

If you run the app now, you notice that your LoopingSelectors are filled with values.
And the result is almost exactly to what the user is used too.
Except the minutes are limited to increments of 15 minutes.

Now the only thing that is still missing is the done button. The idea behind this button is that before navigating back to the previous page, we’ll set the Value property that came with the IDateTimePickerPage interface to the selected time.

private void ApplicationBarDoneButton_Click(object sender, EventArgs e)
{
	int hour = (int) ((ListLoopingDataSource<int>) this.HoursLoopingSelector.DataSource).SelectedItem;
	int minutes = int.Parse((string) ((ListLoopingDataSource<string>) this.MinutesLoopingSelector.DataSource).SelectedItem);
	if (this.AMPMLoopingSelector.Visibility == Visibility.Visible)
	{ 
		string ampm = (string) ((ListLoopingDataSource<string>)this.AMPMLoopingSelector.DataSource).SelectedItem;
		if (ampm == "PM")
			hour += 12;
	}
	Value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, hour, minutes, 0);
	NavigationService.GoBack();
}

You’ll notice that we get the selected hour by casting the datasource back to a ListLoopingDataSource<int>.
The minutes are just a little trickier, since you need to cast the datasource to a ListLoopingDataSource<string> and then parse this string to an int, to use further.
If we’re using a 12 hours system, our AMPMLoopingSelector is Visible, but to create a DateTime object you need provide the hours according to a 24 hours system (so 13 = 1PM, 14 = 2PM, etc), so you need to add 12 hours to the hour value when the user selected “PM” in the AMPMLoopingSelector.
Then right before navigating back you see that we set the Value property, since we’re only displaying times in the TimePicker, I set the date to today.

If you run your app now, you can manipulate the TimePicker as expected. WOHOO ! \o/

The end… finally ! So much trouble for a feature which should have been included by default in the TimePicker by using a “Step” or “Increment” property.

Here’s a code sample that contains all the code of above.

Happy New Year !

Special thanks go out to Johan Peeters who provided the images of the TimePickers !

Implementing a DataTemplateSelector for BingMap Pushpins (of course while using MVVMLight)

You’ll find a lot of examples for DataTemplateSelectors with Listboxes, but you hardly find any with Pushpins for the Bing Maps Control.
After searching for hours but not finding any, I decided to figure it out myself and let “the world” know how I did it.
In fact setting it all up wasn’t difficult so difficult, in fact to get most stuff done I followed this “guide” at Windows Phone Geek.
ScreenshotAfter an hour or so I had all basic ingredients to make it work, but then came the hardest part : finding the correct XAML syntax to display the PushPins correctly.
At first I had pushpins in pushpins, to get rid of those it took about a complete day of trail and error, until I found the missing piece.

Ok, here we go:

For this example I want my map to display a yellow pin with a little man on, which represents my location, a blue pin which displays the name of the location, and a red pin which also displays a name of the location.

First, like the “guide” instructs us, we need the abstract class “DataTemplateSelector”, of which we will derrive our “PushPinDataTemplateSelector” class, this class will then override the “SelectTemplate” function.

public abstract class DataTemplateSelector : ContentControl
{
	public virtual DataTemplate SelectTemplate(object item, DependencyObject container)
	{
		return null;
	}

	protected override void OnContentChanged(object oldContent, object newContent)
	{
		base.OnContentChanged(oldContent, newContent);
		ContentTemplate = SelectTemplate(newContent, this);
	}
}

With this class in place we can now make our PushPinDataTemplateSelector. This class will derrive from the abstract class DataTemplateSelector and we will override the SelectTemplate function. This function in fact just returns a type, which can be found in the Bing Map Control’s available templates. That’s how the magic happens in fact.

public class PushPinDataTemplateSelector : DataTemplateSelector
{
	public DataTemplate RedPin     { get; set; }
	public DataTemplate BluePin    { get; set; }
	public DataTemplate MyLocation { get; set; }

	public override DataTemplate SelectTemplate(object item, DependencyObject container)
	{
		switch (item.GetType().ToString())
		{
			case "PushPinDataTemplateSelectorExample.ViewModel.MyLocation":
				return MyLocation;
			case "PushPinDataTemplateSelectorExample.ViewModel.BluePin":
				return BluePin;
			case "PushPinDataTemplateSelectorExample.ViewModel.RedPin":
				return RedPin;
			default:
				break;
		}

		return base.SelectTemplate(item, container);
	}
}

So, this DataTemplateSelector derrivate is now ready to be used in our XAML.
We still need some other classes to make it work, first a base class of which we will derrive our pushpin types. The structure of this base class depends largly of what you want to display on/as your pushpins. Here’s an example of a “PinLocationBase” class, important is of course the “Location” property which is a GeoCoordinate that holds the position on the map. I added an extra property called Name because I want to display a name in the PushPin.

public class PinLocationBase
{
	public GeoCoordinate Location { get; set; }
	public string        Name     { get; set; }
}

I put this class always in the ViewModel, because most of the time this will be only used for that one page that contains a Bing Map Control, if you have more than one page with a map on, you probably want to move it to your Models.
Now you need some derrived classes of your PinLocationBase class so you can distinguish between your location, a blue pin location or a red pin location. This is very easy since it are actually just aliasses of the PinLocationBase class.

public class MyLocation : PinLocationBase { }
public class BluePin : PinLocationBase { }
public class RedPin : PinLocationBase { }

You can put these 3 classes in the same file as the base class.
Your ViewModel, finally, should contain a property that returns a List, you can use the “mvvminpc” snippit for that, like so:

///
<summary> /// The property's name.
/// </summary>
public const string ListOfPinLocationsPropertyName = "ListOfPinLocations";

private List _listOfPinLocations = null;

///
<summary> /// Gets the ListOfPinLocations property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public List ListOfPinLocations
{
	get
	{
		return _listOfPinLocations;
	}

	set
	{
		if (_listOfPinLocations == value)
		{
			return;
		}

		var oldValue = _listOfPinLocations;
		_listOfPinLocations = value;

		// Update bindings, no broadcast
		RaisePropertyChanged(ListOfPinLocationsPropertyName);
	}
}

You’ll need to fill the List with either MyLocation classes, BluePin classes and/or RedPin classes. I noticed that the best was is to populate a temporary List and then assigning this temporary list to the ListOfPinLocations property.

And now comes what was for me the hardest part : getting the XAML right so it works as wanted, and it doesn’t display a pin in a pin or just nothing. Anyway, here’s some copy+paste XAML for you… you can change the templates to whatever you like.

<BingMap:Map x:Name="MyMap" LogoVisibility="Visible" CopyrightVisibility="Collapsed" ScaleVisibility="Visible" CredentialsProvider="{StaticResource BingMapsAPIKey}" ZoomLevel="10" Culture="{Binding System.Threading.Thread.CurrentThread.CurrentCulture.Parent}" Margin="12,0,12,0">
	<BingMap:MapItemsControl ItemsSource="{Binding ListOfPinLocations}">
		<BingMap:MapItemsControl.ItemTemplate>
			<DataTemplate>
				<BingMap:Pushpin Location="{Binding Location}">
					<BingMap:Pushpin.Template>
						<ControlTemplate>
							<local:PushPinDataTemplateSelector Content="{Binding}">
								<local:PushPinDataTemplateSelector.MyLocation>
									<DataTemplate>
										<Grid>
											<StackPanel Orientation="Vertical">
												<Grid Background="#FFDD2C"
										  		      HorizontalAlignment="Center"
										  		      MinHeight="31"
										  		      MinWidth="17">
													<Image Height="29"
													       Source="pushpins/man.png"
													       Stretch="None"
													       Width="15"
													       HorizontalAlignment="Center"/>
												</Grid>
												<Polygon Fill="#FFDD2C"
												         Points="0,0 17,0 0,15"
												         Width="17"
												         Height="15"
												         HorizontalAlignment="Left"/>
											</StackPanel>
										</Grid>
									</DataTemplate>
								</local:PushPinDataTemplateSelector.MyLocation>
								<local:PushPinDataTemplateSelector.BluePin>
									<DataTemplate>
										<Grid>
											<StackPanel Orientation="Vertical">
												<Grid Background="#003974"
												      HorizontalAlignment="Left"
												      MinHeight="31"
												      MinWidth="29">
													<TextBlock Text="{Binding Name}"
														 Margin="4,4,4,4"
														 HorizontalAlignment="Left"
														 Foreground="White"/>
												</Grid>
												<Polygon Fill="#003974"
												         Points="0,0 29,0 0,29"
												         Width="29"
												         Height="29"
												         HorizontalAlignment="Left"/>
											</StackPanel>
										</Grid>
									</DataTemplate>
								</local:PushPinDataTemplateSelector.BluePin>
								<local:PushPinDataTemplateSelector.RedPin>
									<DataTemplate>
										<Grid>
											<StackPanel Orientation="Vertical">
												<Grid Background="#743900"
												      HorizontalAlignment="Left"
												      MinHeight="31"
												      MinWidth="29">
													<TextBlock Text="{Binding Name}"
														 Margin="4,4,4,4"
														 HorizontalAlignment="Left"
														 Foreground="White"/>
												</Grid>
												<Polygon Fill="#743900"
												         Points="0,0 29,0 0,29"
												         Width="29"
												         Height="29"
												         HorizontalAlignment="Left"/>
											</StackPanel>
										</Grid>
									</DataTemplate>
								</local:PushPinDataTemplateSelector.RedPin>
							</local:PushPinDataTemplateSelector>
						</ControlTemplate>
					</BingMap:Pushpin.Template>
				</BingMap:Pushpin>
			</DataTemplate>
		</BingMap:MapItemsControl.ItemTemplate>
	</BingMap:MapItemsControl>
	<BingMap:Map.Center>
		<System_Device_Location:GeoCoordinate Altitude="NaN" Course="NaN" HorizontalAccuracy="NaN" Latitude="51.0634402162154" Longitude="4.34346499605191" Speed="NaN" VerticalAccuracy="NaN" />
	</BingMap:Map.Center>
</BingMap:Map>

Basically these are all the ingredients you need to make it work… not that difficult, and a lot like the “guide” instructs, like I said, too bad that you can find a lot of ListBox examples, but I needed a Bing Maps Control example which I just couldn’t find.

I’ve added a sample project, so you can see it in action.