Tag Archives: DateTime?

Binding null-value of DateTime to DatePicker

One of my problems with binding a variable of type DateTime to a DatePicker was that the variable, after loading data from a database, might be NULL. The problem is that the value NULL is interpreted from the DatePicker as the 01.01.0001. To change the date, the user has to click through all years or enter the day he want by hand.

The fact that this is very fraught I decided to create a DateConverter class.
In the case when a variable is bound to the DatePicker the Convert method is executed.
If the DateTime taken from the value parameter is not NULL and the value is a valid DateTime, then the method returns the correct date. If not an empty string is returned. The DatePicker handles this empty string like no date. That means he shows by opening it the current month indeed the January 0001.

Note: Before .NET 4.0 you have to download the WPF-Toolkit to use the DatePicker.

Note: As written in the comments, in .NET 4.0 binding null to a DataPicker shows after opening the control the actual month, not as in the WPF-Toolkit the month of the 01.01.0001.

internal class DateConverter : IValueConverter
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        if(value != null)
            return ((DateTime)value).ToShortDateString()
        return String.Empty;

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        string strValue = value.ToString();
        DateTime resultDateTime;
        return DateTime.TryParse(strValue, out resultDateTime) ? resultDateTime : value;

Import the Class into the XAML-Code


Binding data into XAML

<DatePicker Height="25">
        <Binding Path="FieldToBind" UpdateSourceTrigger="PropertyChanged">

Note: Please see my new, and better solution using AttachedProperties by reading the post Binding null-value of DateTime to DatePicker using an Attached Property.


Posted by on February 1, 2010 in WPF


Tags: ,