Search code examples
c#xamldatetimedata-bindingdatetimepicker

How to leave DateTimePicker object blank (Select a date) on load when DateTime is null (01/01/0001) but populate when there is a value?


I'm trying to get a DateTimePicker object to populate with the default text (Select a date) when it doesn't get any date back from the database. If there is a date in the database, the field will populate with that date.

I wroting code that has a two way bind on SelectedDate option to a DateTime property on in the code-behind. It works properly and populates the field with 01/01/0001 since that is the null of DateTime objects. I've tried to changing it to a OneWayToSource and just bind the date if it is greater than 01/01/0001 but it puts a redbox around the object if it doesn't get a date.

Any suggestion?

Thanks for the help everyone! Here is the solution that I found.

[ValueConversion(typeof(DateTime), typeof(DateTime))]
class DateTimeNullConverter: IValueConverter
    {
         public object Convert (object value, Type targetType, object parameter, Culture culture)
         {
                if (value != null)
                {
                   DateTime dateTime = (DateTime)value;
                   if (dateTime.Year.ToString == "1")
                       return null;
                   else
                      return dateTime;
                }
                else
                {
                      return null;
                }
            }

         public object ConvertBack (object value, Type targetType, object parameter, Culture culture)
         {
              DateTime convertDateTime;
              if (value == null)
              {
                  convertDateTime = new DateTime();
              }
              else
              {
                  convertDateTime = (DateTime) value;
              }

              return convertDateTime;
         }
    }

Solution

  • Create a DateBlankConverter converter that binds to the same control:

     <DatePicker x:Name="DatePickerInstance" 
     Visibility="{Binding ElementName=DatePickerInstance, 
     Converter={StaticResource DateBlankConverter}, ConverterParameter={Binding Date}}"/>
    

    And inside the converter check if the date is null to hide or show the DatePicker, or change the property you need.