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 !

Advertisements

18 thoughts on “How to create a TimePicker that goes by 15 minute increments ?

  1. Absolutely Brilliant! 15 or 5 minute increments should have been the default! What user wants to set anything to an exact minute? Works great!

  2. Awesome example, thanks for posting. It works perfectly except that the loopedlist columns don’t fade away after you have made a selection. I tried your sample code (just to make sure I didn’t do something wrong) on my handset and an emulator – both exhibit the same behaviour.

    • You’re right… I noticed that too… you explicitly have to click the numbers you want to select to made it fade away. But I think that’s the control itself.
      i’ll look more into that.

      I noticed too that some of the verification code is not yet 100% ok in the sample nor the blogpost.
      I will adapt both very soon, if I find the time.

      • I was able to fix it by placing the following code inside the ApplicationBarDoneButton_Click function.

        if (ampm == “PM”)
        {
        if (hour != 12)
        {
        hour += 12;
        }
        }else {
        if (hour == 12)
        {
        hour -= 12;
        }
        }

        it seemed to be a problem with the 12 PM actually going past the 24 hour scheme and the 12 AM equalling 12 PM

  3. Hi, i tried ur tutorial but my problem is that after i change the value from the picker do not apply to interface. can i know what code i miss out ?

  4. hi, i still couldn’t get the value from timepicker and your example code is not longer available

  5. I’m implemented this example but Selected DATETIME not update in

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

    Why?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s