Click here to Skip to main content
11,435,451 members (56,310 online)
Click here to Skip to main content

A WPF DateTimePicker That Works Like the One in Winforms

, 9 Sep 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
A WPF DateTimePicker that Works like the one in Winforms

Introduction

When I started moving from Winforms to WPF, there was one control I really missed, and that was the DateTimePicker, as implemented in Winforms. WPF has the datepicker, but what I wanted was a control where you can easily tab from year to month to day, and use the arrow keys to change values.

Note: Qwertie has made an excellent C# version of this control, ironing out the worst bugs in the process. Smile | :) You can check out his version at https://gist.github.com/1150228.

Background

The code plays around with some of the fundamental techniques required when building a user control in WPF.

Using the Code

To use the code, just compile the DTPicker and add a reference to the DLL in your project. (or include the DTPicker project as a subproject to your project. The solution contains two projects; DTPicker, where the usercontrol resides, and TestDTPicker, a small WPF project to test the DateTimePicker in.

XAML

The XAML for the control is pretty straight forward.

 <UserControl x:Class="DateTimePicker"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             xmlns:DTPicker="clr-namespace:DTPicker">
    <UserControl.Resources>
        <ControlTemplate x:Key="IconButton" 
        TargetType="{x:Type ToggleButton}">
            <Border>
                <ContentPresenter />
            </Border>

        </ControlTemplate>
        <DTPicker:BoolInverterConverter x:Key="BoolInverterConverter" />
    </UserControl.Resources>
    
    <StackPanel Orientation="Horizontal">
    
        <TextBox x:Name="DateDisplay" 
                     VerticalContentAlignment="Center" 
                     Margin="0,0,0,0" 
                    MinHeight="{Binding ElementName=PopUpCalendarButton, 
 Path=ActualHeight}" >2001-01-01 12:30</TextBox>
        <ToggleButton Template="{StaticResource IconButton}" 
                      MaxHeight="21" 
                      Margin="-1,0,0,0" 
                      Name="PopUpCalendarButton" 
                      IsChecked="False"
                      IsHitTestVisible="{Binding ElementName=CalendarPopup,
 Path=IsOpen, Mode=OneWay, Converter={StaticResource BoolInverterConverter}}" >

          <Image Source="Calendar.Icon.bmp" Stretch="
          None" HorizontalAlignment="Left"  />
        </ToggleButton>
        <Popup IsOpen="{Binding Path=IsChecked, ElementName=PopUpCalendarButton}" 
               x:Name="CalendarPopup" Margin="0,-7,0,0"
               PopupAnimation="Fade"
               StaysOpen="False">
            <Calendar Margin="0,-1,0,0"
                      x:Name="CalDisplay" ></Calendar>
        </Popup>
    </StackPanel>
</UserControl> 

Code

There are four main variables in our control:

  • SelectedDate - The selected date Smile | :)
  • DateFormat - How this date should be displayed (yyyy-MM-hh etc.)
  • MinimumDate - The minimum date value that can be selected
  • MaximumDate - The maximum date value that can be selected

The interesting thing is that the values of SelectedDate, MinimumDate and MaximumDate are all interconnected. So when declaring the Dependency properties for these, I have to include a coerce callback function.

Public Shared ReadOnly SelectedDateProperty As DependencyProperty = _
                           DependencyProperty.Register("SelectedDate", _
                           GetType(Nullable(Of Date)),
                           GetType(DateTimePicker), _
                           New FrameworkPropertyMetadata(Date.Now,
                           New PropertyChangedCallback(AddressOf OnSelectedDateChanged),
                           New CoerceValueCallback(AddressOf CoerceDate)))  

Here is the CoerceDate function:

  Private Shared Function CoerceDate(ByVal d As DependencyObject, 
 ByVal value As Object) As Object
        Dim dtpicker As DateTimePicker = CType(d, DateTimePicker)
        Dim current As Date = CDate(value)
        If current < dtpicker.MinimumDate Then
            current = dtpicker.MinimumDate
        End If
        If current > dtpicker.MaximumDate Then
            current = dtpicker.MaximumDate
        End If
        Return current
    End Function

Points of Interest

One thing that was hard to figure out was how to move the focus away from my control. It turned out to be an easy oneliner:

Me.MoveFocus(New TraversalRequest(FocusNavigationDirection.Previous)) 

Things That Can Be Done Better

The image of the calendar is encapsulated in the control. Some would probably like to expose the image as a property. Also although SelectedDate is a nullable, I should really write more code to display a default text when there is no SelectedDate.

History

  • 2010-12-02: First attempt to write the article
  • 2011-09-08: Added a note about Qwerties version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Magnus Gudmundsson
Software Developer (Senior) CyberDaDa
Sweden Sweden
Magnús Gudmundsson has been programming on and off since he got his first sinclair spectrum sometimes in the murky 80's.
Currently he is trying to start a company called CyberDada
http://www.cyberdada.com

Nowadays Magnús mostly programs in .Net. He is equally fluent in vb and c#, has done webforms, winforms, webservices, wpf, and then some Smile | :)

Comments and Discussions

 
QuestionGetBindingExpression Pin
is.vlad18-Nov-14 7:50
memberis.vlad18-Nov-14 7:50 
AnswerRe: GetBindingExpression Pin
is.vlad18-Nov-14 8:42
memberis.vlad18-Nov-14 8:42 
GeneralRe: GetBindingExpression Pin
Magnus Gudmundsson18-Nov-14 10:44
memberMagnus Gudmundsson18-Nov-14 10:44 
GeneralRe: GetBindingExpression Pin
is.vlad18-Nov-14 20:40
memberis.vlad18-Nov-14 20:40 
GeneralRe: GetBindingExpression Pin
is.vlad18-Nov-14 20:42
memberis.vlad18-Nov-14 20:42 
GeneralRe: GetBindingExpression Pin
is.vlad18-Nov-14 21:34
memberis.vlad18-Nov-14 21:34 
GeneralRe: GetBindingExpression Pin
Magnus Gudmundsson18-Nov-14 21:53
memberMagnus Gudmundsson18-Nov-14 21:53 
GeneralRe: GetBindingExpression Pin
is.vlad19-Nov-14 2:06
memberis.vlad19-Nov-14 2:06 
QuestionCan't change DateFormat in DataGrid? Pin
Member 372081025-Jan-13 9:49
memberMember 372081025-Jan-13 9:49 
I'm using Qwerties version of this control and having one large issue. When the control is in a DataGrid and I try to change the DateFormat, the binding seems to get messed up and all the dates show as the current time when I open the form. Has anyone else seen this problem? My XAML is below:

<DataGridTemplateColumn Header="Start Time" Width="Auto">
    <DataGridTemplateColumn.CellTemplate >
        <DataTemplate>
            <dtp:DateTimePicker DateFormat="M/d/yyy h:mm:ss tt" SelectedDate="{Binding StartTime, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

SuggestionGood example of WPF DateTimePicker In DataGrid Pin
JohnDetroit3-Jun-12 2:39
memberJohnDetroit3-Jun-12 2:39 
Questionits simple and useful Pin
musto2310-May-12 21:17
membermusto2310-May-12 21:17 
QuestionC# version + improvements [modified] Pin
Qwertie16-Aug-11 12:37
memberQwertie16-Aug-11 12:37 
AnswerRe: C# version + improvements Pin
Magnus Gudmundsson16-Aug-11 20:27
memberMagnus Gudmundsson16-Aug-11 20:27 
GeneralRe: C# version + improvements Pin
Qwertie17-Aug-11 5:28
memberQwertie17-Aug-11 5:28 
GeneralRe: C# version + improvements Pin
Member 1131974118-Dec-14 1:17
memberMember 1131974118-Dec-14 1:17 
GeneralRe: C# version + improvements Pin
Qwertie18-Dec-14 7:37
memberQwertie18-Dec-14 7:37 
QuestionDate format not accepted Pin
John Cserkuti4-Aug-11 4:45
memberJohn Cserkuti4-Aug-11 4:45 
AnswerRe: Date format not accepted Pin
Magnus Gudmundsson4-Aug-11 7:57
memberMagnus Gudmundsson4-Aug-11 7:57 
Generalfunny I did one of these the other day Pin
Sacha Barber3-Dec-10 0:34
mvpSacha Barber3-Dec-10 0:34 
GeneralRe: funny I did one of these the other day Pin
Magnus Gudmundsson3-Dec-10 2:01
memberMagnus Gudmundsson3-Dec-10 2:01 
GeneralRe: funny I did one of these the other day Pin
Sacha Barber3-Dec-10 22:19
mvpSacha Barber3-Dec-10 22:19 
GeneralMy vote of 5 Pin
Dalek Dave2-Dec-10 13:24
memberDalek Dave2-Dec-10 13:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150428.2 | Last Updated 9 Sep 2011
Article Copyright 2010 by Magnus Gudmundsson
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid