Reputation: 83
Is there a way we can set the datepicker value to Empty/Null/blank (it usually defaults to mindate i.e 01/01/0001)
Appreciate your help on this!!
Upvotes: 0
Views: 1127
Reputation: 83
XAML:
Converter: DateTime to null Converter
public class DateTimeToNullConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if(System.Convert.ToDateTime(value).ToLongTimeString() != "12:00:00 AM")
{
return null;
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null || value.ToString() == "")
{
return DateTime.Now;
}
return value;
}
}
}
Use this converter in Text, SelectedDate and Display Date property of a datepicker and then handle the lostfocus relay command in the viewmodel for more validation
private void FromDateLostFocusCommandExecuted(EventArgs args)
{
//ClearValidationErrors();
string inputDate =
((System.Windows.Controls.Primitives.DatePickerTextBox)
(((System.Windows.RoutedEventArgs)(args)).OriginalSource)).Text;
if (inputDate != "")
{
if (!IsValidDate(inputDate))
{
ObservableCollection<string> errors = GetErrorsCollection("FromDate");
errors.Add("Please enter a valid From Date (M/d/yyyy)");
RaiseErrorsChanged("FromDate");
if (!validationErrors.Contains("FromDate"))
{
validationErrors.Add("FromDate");
}
}
else
{
ClearValidationErrors("FromDate");
if (validationErrors.Contains("FromDate"))
{
validationErrors.Remove("FromDate");
}
}
}
else
{
ClearValidationErrors("FromDate");
if (validationErrors.Contains("FromDate"))
{
validationErrors.Remove("FromDate");
}
}
}
Upvotes: 1