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.

As long as you follow “The (Metro) Grid”, you’re good !

On November 3rd – during the Web & Phone UX Tour Belgium, Arturo Toledo meant that we all should follow “The Grid”… it sounded like a famous movie quote, but it’s not.

The Grid” probably got famous by Jeff Wilcox’ MetroGridHelper who saw Arturo and Corrina Black use it as a transparent image to align their controls.  The sad thing about the MetroGridHelper is that it’s only visible in debug mode, and not “while” layouting your app.  So layouting would mean constantly starting your app, see if all is well layouted, making changes, restarting your app, ah, darn, you forgot there something, so adjusting that again, of course restarting the app again to check, well, you get my drift I guess.

During the UX Tour event in Antwerp, I asked Arturo and Corrina if they could make their PNG publically available, they told me they would, so expect that one coming later this weekend (that’s what Corrina told me).

In the mean time, you can use this one, which is in fact just an export of the Expression Designer file Arturo posted a while ago on his blog.  Of course I had to expand the canvas of it, but I had all the heights and widths clearly marked on the Expression Designer file, so that was easy.  I recolored the blue rectangles to red slightly transparent ones too, so it looks more like the MetroGridHelper.

Windows Phone Grid in Red Transparent

Click to download it !

The easiest way to use it, is of course “Add an Existing Item” (the grid you just saved) to your project and then open your XAML Windows Phone Page in Expression Blend, open your Projects tab (the one that shows all the files in your project), and simply drag it on the Windows Phone Page.
Then just make sure it’s the lowest object in your Objects and Timeline panel, all the way at the bottom of the LayoutRoot object.  Also make sure to set all Margins to 0, else, of course it’s useless.
Expression Blend will generate the following line of XAML which perfectly does the trick !

<Image Height=”800″ Margin=”0″ Grid.Row=”1″ Source=”WindowsPhone_Grid_red_transparent.png” Stretch=”None” VerticalAlignment=”Bottom”/>

Don’t forget to remove these lines and image from your Windows Phone Pages when publishing your app !

A BIG thank you goes out to Corrina Black and Arturo Toledo, you now can also make perfect Windows Phone design as long as you follow “The Grid” !

Create your own Implode!XL-clone – Designing the game

Just like the Game Development Tutorial on the App Hub we’ll start “thinking” about – or as in this case “analysing” – the game.

To get the analysis proses started, let’s begin with answering the question they propose:

  • What kind of game is it ?
    It’s a puzzle game, puzzle’s are solved when the game objective is reached.
  • What is the game objective ?
    A player has won, when the house has been destroyed, and all debris is stacked lower than a certain height and the debris hasn’t touched any of the side buildings.
    A game is lost if : a side building is touched by debris, or when all debris came to rest and the minimum height is not reached.
  • What are the gameplay elements ?
    A player places bombs on the blocks that form the building.  There are several sort of bombs, those that explode in different directions (like up, left or right) or those that generate different sized explosions.
  • What are the engineering elements ?
    The blocks fall just like in the real world, that’s what makes the game so much fun.  This means that physics are involved… unfortunately we all didn’t really pay attention enough back in school, to remember all rules of physics.  But we’re lucky because some clever people did remember everything from their physics course, and implemented those things in what they call a “physics engine”.  The most popular for Windows Phone is the open source Box2D implementation called : Farseer Physics Engine.
    You will notice that the physics engine is in fact just an “aid”, it’s a bit weird to comprehend this in the beginning – but in fact the physics engine does nothing else than a lot of calculations.
    To represent what happens in your game world you need to draw things to the screen… to maintain what happens when, with what object you will set up and use an object model.
  • What art assets do you need ?
    We will probably have a several art assets in our game, things like the blocks, the bombs, the user interface, buttons, etc…
    I prefer not to use the art assets yet, I want to get the basics up and running before adding all the eye candy.
    The Farseer Physics Engine contains what they call a “debug view”, this is a project that is included with Farseer physics XNA Samples projects zip file.  You can use this project to visualize what’s going on in your World… later on we will “paste” beautiful graphics over every object in the physics World.
    We also might need audio assets, no game is much fun without sounds of bombs, falling blocks, etc

Let’s create a flowchart of the game… take a look at the example on the Game Development Tutorial on the App Hub.
You will see that they use ellipses for program states (launch game, exit game, game, game over), rectangles for game loop actions (main menu, check for input, movement input registered, fire bullet, check for collisions, bullet collides with enemy, player collides with enemy, draw), and rectangles with double side lines for sub-actions (initialize …, increase …, draw …, play <sound>, update …, highlight …).
If you start your Meesoft Diagram Designer, you’ll see all these “objects” too on the right hand side.  Drag a Terminator ellipse on the drawing surface.  To change the text right-click it, and type “Launch game”.

Let’s do the same for our Implode!XL clone.

When the game start, the user will see a main menu, where he can choose to start the game, or change the audio settings (music on/off and sfx on/off).  When he chooses to start a game, he’s presented a level selector first, where he chooses the level to play.  Then the game will start.
We’ll first check for user input, for our Windows Phone game it’ll mean check if a user touched the screen.  If the user touched (and held) the bomb stock we initialize a new bomb of that type, decrement the bomb stock with 1, and start dragging the bomb around.  If the bomb touches a block, and the user stops the dragging motion, the bomb should snap to the block.
If the user touched the trigger, we’ll cut the blocks that have bombs on them, and then we’ll explode the bomb, this will give the impression that the bomb cut the block.
In the next step we will do some collision detection… of course the physics engine will take care of the collision detection itself, but we want to do things when collisions are detected, like playing sounds.
Then we’ll check if the level is won or lost.  This is probably the most difficult phase of the game.  We need to find out what is the highest point of our debris, then we need to verify if that height is lower than our minimum height that is defined by the level.  We’ll check if the blocks are still falling/moving, if they still are, then it might be normal that we’re not below the minimum height yet.
A timer will be set, when the blocks are not moving anymore and/or when the debris height is below the level defined minimum height.
Last but not least, we’ll draw everything on the screen.

This is it for today.  I think we now have a good idea of how our game will work.
In the next articles we will be talking about how to “write” the game.

Overview

Below you’ll find a list of chapters I’m planning to write… Titles might still change, chapters might me added too.

  1. Introduction
  2. Getting started
  3. Designing the game
  4. Developing the game
    1. I’m sure here will be several sub-chapters
    2. things like:
    3. creating game logic
    4. creating graphics
    5. adding sound
    6. etc
    7. come immediately to mind
  5. Testing the game
    1. Also here I see several sub-chapters, like
    2. the mom/wife test
    3. or even worse : let the baby play with it
  6. Publish the game

Create your own Implode!XL-clone – Getting started

To really get started, we first need to know why we are doing this, instead of just to wait for the official game to show up in the Marketplace.
Personally, I started this series, because:

  • I like the Windows Phone
  • I’m a developer, so I wanted to develop something for my phone
  • I always wanted to create a game
  • I wanted to learn XNA – it makes creating games accessible for .NET developers.
  • I wanted to learn more about Windows Phone – Mango
  • my wife isn’t convinced that I could create a game like Implode!XL
  • I wanted something to show off to friends and colleagues on my phone

If any of the reasons above applies to you too, I think you’re good to stay for a while !

I don’t have too much time per day to work on this series, since I’m not doing XNA or Windows Phone (yet) as a day job.  Above that my 2,5-year-old daughter asks a lot of attention at the evenings from her daddy.  But I promise to find some time during the weekends to work on this – like right now.

Because of my schedule, I decided to focus on Mango, I thought it’ll take a few months to get the game finished, so when Mango is officially released my game should be ready, so why not immediately enjoy the fast application switching, XNA and Silverlight integration, more than 30 fps in XNA, and all the other goodies that can be found in Mango ?

So, to get started you need :

  • The latest Windows Phone SDK 7.1 – currently this is beta 2
  • If you have inferior hardware, like I do, (4  year old laptop) I recommend upgrading your Windows Phone to Mango too.  To do so, you need to be registered developer, you still can register as a developer, Microsoft will then tell you how to upgrade your phone.
  • To create a flow chart of the game we’ll use Meesoft Diagram Designer, which is a freeware tool.  Download and install it, you’ll need it !
  • Since the game is mimicking real world physics make sure you download the Farseer Physics Engine from codeplex – or use NuGet to download the engine.
  • Download the Farseer Physics Engine XNA Samples, it contains the DebugView project to make things visible.
  • I will use C#, since I prefer that language, if you’re a VB.NET developer, you’re probably used to read C# and translate that into VB.NET

Have you got all that ?  Then let’s get started…

Overview

Below you’ll find a list of chapters I’m planning to write… Titles might still change, chapters might me added too.

  1. Introduction
  2. Getting started
  3. Designing the game
  4. Developing the game
    1. I’m sure here will be several sub-chapters
    2. things like:
    3. creating game logic
    4. creating graphics
    5. adding sound
    6. etc
    7. come immediately to mind
  5. Testing the game
    1. Also here I see several sub-chapters, like
    2. the mom/wife test
    3. or even worse : let the baby play with it
  6. Publish the game

Create your own Implode!XL-clone – Introduction

This is the start of a new series, which follows the now popular Windows Phone trend of “do it yourself iOS game name goes here>”.
A Twitter friend of mine called Jo De Greef already created a “Making Your Own WP7 Angry Birds” series.
I wanted to do something similar but with a game I played a lot on the iPad, called Implode!XL by IUGO.

Implode!XLImplode!XLI saw in a Windows Phone XBOX Live commercial that this game is coming to our phones too… yes, even the website confirms it.  Of course our game won’t be as polished as the commercial game, but it might get very close though…

The goal of the game is to explode a structure – mostly house shaped -and to make sure the debris remains below a certain minimum height, or doesn’t touch another structure which is close by.
Sounds easy, but sometimes it can be very challenging, especially making sure you don’t break the neighbours’ windows.

I will follow the Microsoft best practices guidelines of the Game Development Tutorial, since I think it’s always best to plan before you start developing, above that, the “plan” will guide our development, and by so we won’t forget anything.

See you in the next part !

Overview

Below you’ll find a list of chapters I’m planning to write… Titles might still change, chapters might me added too.

  1. Introduction
  2. Getting Started
  3. Designing the game
  4. Developing the game
    1. I’m sure here will be several sub-chapters
    2. things like:
    3. creating game logic
    4. creating graphics
    5. adding sound
    6. etc
    7. come immediately to mind
  5. Testing the game
    1. Also here I see several sub-chapters, like
    2. the mom/wife test
    3. or even worse : let the baby play with it
  6. Publish the game

Installed Mango on my Samsung Omnia 7

Just after I succeeded to upgrade to 7392, Microsoft announced to possibility to upgrade to Mango if you were a registered Windows Phone Developer.  Best spend $ 99,00 !

Below are my findings so far, after toying around with Mango.

User Experience: Finally we (in Belgium) have the “Marketplace > apps” link in Zune ! We already had the Marketplace on the phone, but never in Zune.
I tested on the way home from the supermarket how the turn-by-turn guidance works in the Maps application, I was impressed… of course the phone speaks English instead of dutch to me, but hey, you can’t have it all, can you ?
Shortly after the upgrade I sent a text message to my wife, stating that I love her, without touching the phone – that texting by voice is pretty impressive, actually I’m blown away by that… I wonder if that works in other languages than English too… I’m thinking about French, since my wife is francophone.

Developer Experience: after installing Mango, my phone is locked again ?  Strange.  But thanks to the “Windows Phone Developer Registration” not a big problem.
I just read that the XNA games are no more limited to 30 fps, that sounds great.

I think this is pretty much it from the updating my Samsung Omnia 7 front until the official release of Mango at least.
I will start an XNA tutorial series for the Windows Phone soon, much like a twitter friend of mine Jo De Greef who wrote a “Making your own WP7 Angry Birds” series.