DatePicker System.FormatException

pap*_*zzo 10 wpf datepicker formatexception

在这个DatePicker中,如果我输入无效日期,如
1/1/20001(输入密钥),
我会得到以下异常

mscorlib.dll中发生了'System.FormatException'类型的第一次机会异常

附加信息:字符串未被识别为有效的DateTime.

但看起来这是由绑定引发的,我找不到处理它的方法.
在调试中,我在屏幕上得到了上述内容

打开堆栈跟踪,它说在SearchItem.Date1上抛出错误
但是问题是在那种情况下实际上没有调用get

如果我输入一个有效的日期,例如1/1/2000,我会看到设置和调用.

如果我输入无效日期,则无需设置调用.

我输入和无效日期并按输入或丢失焦点只是恢复到前一个日期并且不会抛出异常.如果先前的日期为null,则它将恢复为null.

这对我来说是一个关键问题,如果用户输入有效日期然后输入无效日期,则DatePicker只会恢复到上一个​​有效日期.因此用户不知道日期没有改变.

问题是如何处理无效的日期异常?

<DatePicker Width="140" DisplayDateStart="1/1/1990" DisplayDateEnd="12/31/2020" 
            SelectedDate="{Binding Path=Date1, Mode=TwoWay, ValidatesOnExceptions=True, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"/>
Run Code Online (Sandbox Code Playgroud)

如果我拿出来

, ValidatesOnExceptions=True, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged  
Run Code Online (Sandbox Code Playgroud)

没有什么变化

private DateTime? date1; 
public DateTime? Date1
{
    get
    {
        try
        {
            return date1;
        }
        catch (Exception ex)
        {
            return (DateTime?)null;
            throw;
        }
    }
    set
    {
        if (date1 != value)
        {
            date1 = value;
            NotifyPropertyChanged("Date1");    
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Bah*_*ies 8

我能想到的一种方法是使用DateValidationError事件:

XAML:

<DatePicker Width="140" DisplayDateStart="1/1/1990" DisplayDateEnd="12/31/2020" 
            SelectedDate="{Binding Path=Date1, Mode=TwoWay, 
            ValidatesOnExceptions=True, ValidatesOnDataErrors=True, 
            UpdateSourceTrigger=PropertyChanged}"
            DateValidationError="DatePicker_DateValidationError" />
Run Code Online (Sandbox Code Playgroud)

代码背后:

private void DatePicker_DateValidationError(object sender, DatePickerDateValidationErrorEventArgs e)
{
    // throw FormatException
    e.ThrowException = true;

    //OR

    // handle the exception by showing message and clearing data
    MessageBox.Show(e.Exception.Message);
    ((DatePicker)sender).Text = null;
}
Run Code Online (Sandbox Code Playgroud)