WPF DatePicker - How to bind a WPF DatePicker object to a DataView field of DateTime data type?

Oct 7, 2009 at 9:20 PM
Edited Oct 7, 2009 at 9:24 PM


I'm trying to bind a DatePicker object to a field of datetime type that belongs to a DataView object. What's the best way to accomplish this? I am using a WPF DatePicker object (not the tradicitional Windows Form 2.0 control DateTimePicker).

I was doing something like this:

where dTPDateRequested is a DatePicker object. The problem with below code is that while it allows me to display the date in the window, it doesnt update the source. Any ideas?

DateTime SourceRequestedDate;
if (DateTime.TryParse(_justificationView[0].Row["requested_datetime"].ToString(), out SourceRequestedDate))
       dTPDateRequested.SelectedDate = Convert.ToDateTime(_justificationView[0].Row["requested_datetime"]);
     dTPDateRequested.SelectedDate = DateTime.Now.Date;
     _justificationView[0].Row["requested_datetime"] = DateTime.Now.Date;

Oct 7, 2009 at 9:45 PM


I got it...

First you edit the XAML like this: 

<my:DatePicker Height="31" HorizontalAlignment="Right" Margin="0,86,18,0" Name="dTPDeliveryDate" VerticalAlignment="Top" Width="116" xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit" SelectedDateChanged="dTPDeliveryData_SelectedDateChanged" SelectedDate="{Binding estimated_delivery_date}"/>

You bind the SelectedDate property to the name of the column in the DataView that contains the date you are looking for (in this case, the column is called "estimated_delivery_date"). Then you go to the actual C# and do a DataContext to bind the field with the DataView itself. What this does is it tells the compiler what CLR object you are binding your DatePicker field to:

dTPDateRequested.DataContext = _justificationView;

That's it! You might want to perform validations before setting the value so if the date comes as NULL, you do some validation and update field to current time, for example.