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?
01/01/0001 00:00:00in the method convert - Lamloumi Afifnullvalue, butDateTime.MinValue(or a default-constructed DateTime) instead. If it would hold a null value, the cast expression(DateTime)valuewould throw on exception. - Clemens