Time Picker

While posting in the MSDN Forums of WPF, I received a lot of requests to create a TimePicker. So here it is finally, a simple yet extensible TimePicker. This control lets the user select a specific time by enter text in 3 textboxes (Hour, Minutes and Seconds). The user can also increment or decrement the time by pressing the Up and Down keys of the keyboard or even by clicking the up and down buttons that are supplied in the control. To make the user experience better when the user clicks the left or right key the focus of the textboxes changes, for example if the user is in the hours textbox and clicks the left key (if the caret index is at the end of the text) the minute text box will get focus. The Time Picker control also rounds the numbers that the user enter, for example if the user enters “88″ in the hours text box the Time Picker rounds this number to 23 (which is the highest number you can have for the hours textbox)

The Time Picker also supports ControlTemplates. There are 5 parts that you can use in your control template

->PART_Hours. This is the hours textbox you must supply this field so that the TimePicker can hook to the focus events and the text input events to change the time when text is enetered. When using this part the Time Picker will take care of adding the behaviour of focusing the next textbox when the left/right key is enetered etc..

-> PART_Minutes. This is the minutes textbox. This field is also needed for the Time Picker to change the time when text is entered. Again when using this field the time picker will hook to the events to get the behaviour mentioned above for the PART_Hours

-> PART_Seconds. This is the seconds textbox. This field is also needed for the Time Picker to change the time when text is entered. Again when using this field the time picker will hook to the events to get the behaviour mentioned above for the PART_Hours

->PART_IncreaseTime. This is a button that must be supplied to increment the time when the user click the button

->PART_Decrement. This is a button that must be supplied to decrement the time when the user click the button

Again this is a basic implementation of the TimePicker, nothing special but it is a start. I would really appreciate feedback so that I can enhance this control and maybe add some new features…

Feel free to download the code and play around with this control…

See also DatePicker
See alse DateTimePicker

Regards

TimePicker

DOWNLOAD SOURCE CODE

WPF Commands

WPF Commands are a really nice way how one can re use functionality of the application. In the demo project that is supplied with this article I have an example of a project that uses the WPF Commands Pattern in order to be able to sort customers. The application has different controls that invoke the same functionality.

To use the WPF Commands you have to declare the command that you are going to use, with a static declaration. When you declare the command you can also specify Input Gestures that can invoke the command (The input gestures invoke the command if there is a command binding, this is explained further down in these post). You can think of input gestures as shortcuts. These are basically a key or even a combination of keys. In the example I use the F3 key as input gesture.

/// <summary>
/// Command to sort the Customers
/// As ou can see the command also hooks to the F3 key of the keyboard
/// </summary>
public static RoutedUICommand SortCustomers = new RoutedUICommand(“SortCustomers”,
“SortCustomers”, typeof(CommandsDemo), new InputGestureCollection(
new InputGesture[] { new KeyGesture(Key.F3, ModifierKeys.None, “Sort Customer”) }));

In the demo project I created the command in the same class as my user interface Window(CommandDemo.cs). In a real life project I would suggest that the command is declared somewhere more central so that other Windows/Components can use the same command. For example if in my project I had another Window that can sort customers I would have created a class that has the command inside. By doing this the command would be accessibly from the other Window as well. You can think of commands as being similar to events. Someone executes the command and someone handles the command. The way I picture this in my head is…

“There are 3 guys Jon, Mark and Patrick that work in a store. The manager of the store decides that Patrick should wash the floor. Jon says “Wash Floor” and Patrick does it. Mark says “Wash Floor” and Patrick does it. So basically Patrick is the Command Handler and Jon, Mark are executing the command causing Patrick(the command handler) to do the operation. The manager that said that Patrick should wash the floor is the Command Binding. This is a very basic explenation of how this pattern works.. Maybe a more confusing one!!!By the way I was going to forget. The RoutedCommand in WPF is similar to RoutedEvents. The caller raises (executes) the command and the command routes up in the WPF Visual Tree until a CommandBindinging handles the command. You can stop the route by setting the e.Handled = true in the command handler.

Now let us continue.. So after defining the command what you have to do is to create the command binding. So basically this implies that you need to specify who is going to do the operation. You do this by creating the following

//Here we create handle the command binding for the whole window
//so which ever control invokes this command the same handler will handle the command
CommandBindings.Add(new CommandBinding(SortCustomers, SortCustomersHandler));

Where SortCustomersHandler is a delegate that is invoked when the command is executed (i.e. When Jon/Mark say “Wash Floor”)//handler for the Sort Customers command.

//this event handler will be invoked when some element will execute the SortCustomers Command
private void SortCustomersHandler(object sender, ExecutedRoutedEventArgs e)
{
//default the sort if no parameter is passed
string sortBy = e.Parameter == null ?
“Name” :
e.Parameter.ToString();
//get the view for the list
ICollectionView view = CollectionViewSource.GetDefaultView(customerList.ItemsSource);
view.SortDescriptions.Clear();
//add the new sort description
view.SortDescriptions.Add(
new SortDescription(sortBy, ListSortDirection.Ascending));
view.Refresh();
}

So what is left for us to do is to create the Mark and Jon that are actually executing the command. Some controls like the button have a command property where you can specify what command to use when the button is clicked (you can even pass a parameter to the command by using the CommandParameter property).

Command=”local:CommandsDemo.SortCustomers” You can even execute the command manually from C# by doing using the following code ICommand command = SortCustomers;
command.Execute(“Name”);

Part 2 – Can Execute
The WPF Command has another cool feature, the CanExcute. This is basically a way how you can check if the command should execute or not. This is a very handy feature if you have a command that can only be executed under certain conditions.
Example:You have a list of users in a ListBox. You want to be able to delete a user. You define a command that as parameter takes the user id. You determine which user to delete by getting the selected item of a ListBox and passing that id as the command parameter. You want the command to execute only if a user is selected. The handler is defined as follows.

//handler for the Can execute chack of the delete customer
private void CanExecuteDeleteCustomer(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = e.Parameter !=
null && e.Parameter is Customer; ;
e.Handled =
true;
}

All controls that support the command pattern (such as the Button) handle the result of the CanExecute by disabling the control if CanExecute is false. If the control which invokes the command does not support the Command pattern don’t worry because a command will only execute if the CanExecute is true. Yet there can be cases where you want to do an action if the command cannot be executed (for example change the visibility of the control or change the text of the control). You can do this be handling the CanExecuteChanged event of the command. In the event handler of the CanExecute changed you have to call the CanExecute method of the ICommand in order to check what is the current state of the command.

bool canExecute = command.CanExecute(paramterForCommand);

I created a helper method that accepts an ICommandSource and gives back the can execute state of the Command. You can use this method to verify the state of the command as shown in the demo.Ok. I think that’s it for now… I hope that this post gives you a better understanding of how commands work and how you can use them to make your application code better. Feel free to download the demo project that I have created for this post in order for you to visualize better how you can us ethe Command Pattern of WPF.

Regards

DOWNLOAD DEMO PROJECT