Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding a nullable datetime within WPF application

I have a wpf application in which I had this property to bind to a datepicker

public Nullable<System.DateTime> dpc_date_engagement { get; set; }

So I add a converter :

 public 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;
       }
   }

In XAML file :

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

The problem is when the date is null, the displayed text is 1/1/0001.

  • How can I fix my code to display an empty string instead of 01/01/0001, for null values?
like image 642
Lamloumi Afif Avatar asked Oct 28 '25 10:10

Lamloumi Afif


1 Answers

The easiest way I've been found to handle nullable DateTime field using in a DatePicker is setting TargetNullValue=''

In XAML file:

<DatePicker Text={Binding dpc_date_engagement, Mode=TwoWay, TargetNullValue='', UpdateSourceTrigger=PropertyChanged} />
like image 182
Jorge Villalobos Avatar answered Oct 29 '25 23:10

Jorge Villalobos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!