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.
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} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With