RSS

Tag Archives: DatePicker

Binding null-value of DateTime to DatePicker using an Attached Property

As you have seen in the post Binding null-value of DateTime to DatePicker  you could not bind a DateTime to a DatePicker without drawbacks. Because if you bind a non nullable DateTime, you will get after opening the DatePicker Popup the Calendar date range near the date 01.01.0001. To avoid that you can use the solution in the linked article or with my new solution using an AttachedProperty. With that one if the bound DateTime, which is not nullable, is DateTime.MinValue, the DatePicker shows on opening the Popup, on which you select a date, the actual date.

On the following picture you see left the situation if you bind a DateTime direct do a DatePicker, right the situation if you do it using my AttachedProperty.
image

<StackPanel Orientation"Horizontal" Height="30" VerticalAlignment="Top">
    <DatePicker Width="300" 
                SelectedDate="{Binding Path=SelectedDateTimeWhichIsNonNullable}" 
                WPFToolkit:CustomAttachedProperties.ShowNullWhenDateTimeMinValue="True">
    </DatePicker>
    <DatePicker Width="300" 
                SelectedDate="{Binding Path=SelectedDateTimeWhichIsNonNullable}">
    </DatePicker>
</StackPanel>

The logic for the AttachedProperty looks like:

public static class CustomAttachedProperties
{
    public static readonly DependencyProperty ShowNullWhenDateTimeMinValueProperty = 
                     DependencyProperty.RegisterAttached("ShowNullWhenDateTimeMinValue", 
                                        typeof (bool), 
                                        typeof (CustomAttachedProperties),
                                        new PropertyMetadata(default(bool),
                                        SetShowNullWhenDateTimeMinValueChanged));

    private static void SetShowNullWhenDateTimeMinValueChanged(DependencyObject d, 
                                           DependencyPropertyChangedEventArgs e)
    {
        DatePicker control = (DatePicker)d;
        if ((bool)e.NewValue)
        {
            control.SelectedDateChanged += OnSelectedDateChanged ;
        }
        else
        {
            control.SelectedDateChanged -= OnSelectedDateChanged ;
        }
    }

    public static void SetShowNullWhenDateTimeMinValue(UIElement element, bool value)
    {
        element.SetValue(ShowNullWhenDateTimeMinValueProperty, value);
    }

    private static void OnSelectedDateChanged (object sender, SelectionChangedEventArgs e)
    {
        UIElement control = (UIElement)sender;

        if ((bool)control.GetValue(ShowNullWhenDateTimeMinValueProperty))
        {
            var currentSelectedDate = ((DateTime?)control.GetValue(DatePicker.SelectedDateProperty));
            if (currentSelectedDate.HasValue && currentSelectedDate.Value == DateTime.MinValue)
            {
                //currently set DateTime.Now that the DatePicker opens the Popup with the current month
                control.SetValue(DatePicker.SelectedDateProperty, DateTime.Now);
                control.SetValue(DatePicker.SelectedDateProperty, null);
            }
        }
    }

    public static bool GetShowNullWhenDateTimeMinValue(UIElement element)
    {
        return (bool)element.GetValue(ShowNullWhenDateTimeMinValueProperty);
    }
}
 
3 Comments

Posted by on May 31, 2012 in C-Sharp, WPF

 

Tags:

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

    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.

 
17 Comments

Posted by on February 1, 2010 in WPF

 

Tags: ,