DatePicker System.FormatException

时间:2014-12-23 18:10:47

标签: wpf datepicker formatexception

在此DatePicker中,如果我输入无效日期,例如
2000年1月1日(输入密钥)
我得到以下异常

  

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

     

其他信息:字符串未被识别为有效的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}"/>

如果我拿出

, ValidatesOnExceptions=True, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged  

没有任何改变

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

1 个答案:

答案 0 :(得分: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" />

代码背后:

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