0

有没有办法可以将 datepicker 值设置为 Empty/Null/blank (它通常默认为 Mindate 即 01/01/0001)

感谢您对此的帮助!

4

1 回答 1

1

XAML:

转换器:DateTime 到 null 转换器

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

在日期选择器的 Text、SelectedDate 和 Display Date 属性中使用此转换器,然后在视图模型中处理 lostfocus 中继命令以进行更多验证

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");
            }
        }
    }
于 2012-04-18T14:29:15.850 回答