RSS

Binding null-value of DateTime to DatePicker

01 Feb

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

    xmlns:converter="clr-namespace:PathToTheFolderWhereTheClassDateConverterIs2

Binding data into XAML

<DatePicker Height="25">
    <DatePicker.Text>
        <Binding Path="FieldToBind" UpdateSourceTrigger="PropertyChanged">
            <Binding.Converter>
                <converter:DateConverter>
            </Binding.Converter>
        </Binding>
    </DatePicker.Text>
</DatePicker>

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.

Advertisements
 
17 Comments

Posted by on February 1, 2010 in WPF

 

Tags: ,

17 responses to “Binding null-value of DateTime to DatePicker

  1. Leonid Kryvoruchko

    September 26, 2011 at 15:52

    you can use [DateTime?] type and DateTimePicker control works fine – displaying nothing if null comes.

     
    • michaelmairegger

      September 26, 2011 at 19:30

      Thanks for the reply.
      in WPF there is no build in DateTimePicker.
      But thanks to you i saw, that null is currently working as DateTime for the build in DatePicker.
      But this was not in the WPF Toolkit that I have used. Unfortunately I did not checked whether the issue was resolor not (in .NET 4). Fortunately it is.

      Ok, i double checked it. null always worked, but if you bind DateTime then you will get the 01.01.0001 instead of no date. Nowadays I did not use this snipped. I use a DateTime? property that wraps the DateTime property instead.

       
  2. Robert Kamarowski

    October 13, 2015 at 16:34

    I have the following XAML code:

    SelectedDate=”{Binding Path=DatePurchased, Mode=TwoWay, Converter=DateConverter}”

    And I’m getting the message:

    The TypeConverter for IValueConverter does not support converting from a string

     
    • Michael Mairegger

      October 13, 2015 at 17:05

      You have to write … Converter={StaticResource DateConverter} … otherwise DateConverter is treated as string
      Additionally to this step you have to define the DateConverter resource with x:Key=”DateConverter”

       
  3. Robert Kamarowski

    October 13, 2015 at 19:47

    I have the following in App.xaml:

    I’m getting a ‘The name DateConverter does not exist in the namespace clr-namespace:Utilities’

    Yet, when I type <u: intellisense brings up DateConverter. I've tried deleting the .sou file and restarting Visual Studio but still doesn't work.
    C# 6.0
    Visual Studio 2015

     
    • Michael Mairegger

      October 21, 2015 at 16:29

      What is the error message that the compiler Shows?

       
      • Robert Kamarowski

        October 25, 2015 at 15:34

        The name DateConverter does not exist in the namespace ‘clr-namespace:Utilities’

         
  4. Robert Kamarowski

    October 13, 2015 at 19:49

    The entries for App.xaml were removed by the message. I’ll try again:

    xmlns:u=”clr-namespace:eesUtilities”

     
  5. Robert Kamarowski

    October 13, 2015 at 19:49

    The other part is:

     
  6. Robert Kamarowski

    October 13, 2015 at 19:50

    I’m sorry, it keeps deleting the text:
    u:DateConverter x:Key=”DateConverter”

     
  7. Robert Kamarowski

    October 27, 2015 at 17:54

    The following code:

    SelectedDate=”{Binding Path=DatePurchased, Mode=TwoWay, Converter={StaticResource ResourceKey=DateConverter}}”

    is producing error:

    An object of the type System.Object cannot be applied to a property that expects the type System.Windows.Data.IValueConverter

     
  8. Robert Kamarowski

    October 28, 2015 at 19:38

    Michael, I have defined the converter in App.xaml:

    Application x:Class=”eesPhotography.App”
    xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
    xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
    xmlns:u=”clr-namespace:eesUtilities”
    xmlns:local=”clr-namespace:eesPhotography”
    StartupUri=”MainWindow.xaml”
    Application.Resources

    u:DateConverter x:Key=”DateConverter”/

     
    • Michael Mairegger

      October 29, 2015 at 09:43

      Then using your binding =”{Binding Path=DatePurchased, Mode=TwoWay, Converter={StaticResource ResourceKey=DateConverter} should work

       
  9. Robert Kamarowski

    October 29, 2015 at 13:46

    Here is the code:

    DatePicker x:Name=”datePickerTableEditPurchased”
    Grid.Column=”1″
    Grid.Row=”7″
    Binding.SourceUpdated=”{Binding Path=DatePurchased, Mode=TwoWay, Converter={StaticResource ResourceKey=DateConverter}}”
    Binding.TargetUpdated=”{Binding Path=DatePurchased, Mode=TwoWay, Converter={StaticResource ResourceKey=DateConverter}}”
    Width=”150″
    Margin=”-40,0,0,0″/

    The bindings are underlined, and when I hover the mouse over the code I’m getting:

    An object of the type System.Object cannot be applied to a property that expects the type System.Windows.Data.IValueConverter

     
    • Michael Mairegger

      October 30, 2015 at 15:01

      Can you provide a small sample project where the code Fails? Just by looking your lines it seems everything ok. Maybe the error is something else.

       
  10. Robert Kamarowski

    October 30, 2015 at 18:42

    My email is rkamarowski@yahoo.com If you want to send me your email I can put a zip file on OneDrive.

    thanks.

     

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: