Wednesday, March 14, 2012

WPF DateTimePicker In DataGrid


Problem:

Need to integrate DateTimePicker control into datagrid cell.
Datagrid with DateTimePicker

Solution:

For some business applications regular WPF DatePicker is not enough, sometimes you need also time and seconds.
I was quite surprised when figured out that .NET Framework 4.0 does not have such control as DateTimePicker.
Well, fortunately there is such a thing called Extended WPF Toolkit.
All you need is download it and to add reference to WPFToolkit.Extended.dll in your WPF project.
Here is how you use DateTimePicker with DataGrid:


First of all don`t forget to add the reference in your XAML file.
xmlns:wpfx="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit/extended"
This is how you integrate it inside DataGrid cell:
<datagridtemplatecolumn Header="Next Run" SortMemberPath="NextRun">
 <datagridtemplatecolumn.celltemplate>
  <datatemplate>
   <wpfx:datetimepicker Format="Custom" 
                        FormatString="M/d/yyyy h:mm:ss tt" 
                        Height="Auto" 
                        HorizontalAlignment="Left" 
                        IsEditable="False" 
                        IsEnabled="{Binding EditMode}" 
                        Name="dateTimePicker1" 
                        Value="{Binding Path=NextRun, 
             UpdateSourceTrigger=PropertyChanged, 
             Mode=TwoWay, 
             ValidatesOnExceptions=True, 
             NotifyOnValidationError=True}" VerticalAlignment="Top" width="175">
   </wpfx:datetimepicker>
  </datatemplate>
 </datagridtemplatecolumn.celltemplate>
</datagridtemplatecolumn>
SortMemberPath property of DataGridTemplateColumn allows you to sort rows.
You just need to bind it to the same property to which DateTimePicker is binded.
Download example source code - (Visual Studio 2010 Project) 

5 comments:

  1. I understand your posting is to demonstrate DateTimePicker in DataGrid in WPF.

    how about my posting here?
    http://www.codeproject.com/Questions/363201/DateTimePicker-in-DataGridView

    say, we load from database, is it possible to edit the datetime with Calendar control or DateTimePicker control?

    ReplyDelete
    Replies
    1. With DateTimePicker control from Extended WPF Toolkit you can anything - date, time, seconds...

      Delete
  2. This didn't work for me I get

    "The tag 'DateTimePicker' does not exist in XML namespace 'http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit/extended'. Line 2171 Position 50.'

    ReplyDelete
  3. You probably forgot to add reference to WPFToolkit.Extended.dll
    I updated the post with downloadable source code example.
    It should work for you.

    ReplyDelete
  4. hi
    this is what i'm searching for. My question is: if the row in Datagrid is edited and CellEndEdit event is raised how do i get the updated datetime out of the cell?
    hape

    ReplyDelete