#1,039 – Intercepting Bad Date Strings Entered into a DatePicker
March 28, 2014 1 Comment
When a user manually enters a date into a DatePicker, the DatePicker control automatically checks to see whether what they entered is a valid date. If the date is valid, it’s converted to the proper display format and the DatePicker’s SelectedDate property is set.
If the date is not valid, the DatePicker by automatically reverts to the last valid string contained in this field, or to an empty string.
You can react to the user entering an invalid date by handling the DateValidationError event.
For example, if we have a bindable string property ErrorMessage, we can do the following:
<Label Content="Pick a date:" Margin="5"/> <DatePicker Margin="5,0,5,5" DateValidationError="DatePicker_DateValidationError" SelectedDateChanged="DatePicker_SelectedDateChanged"/> <TextBlock Margin="5" Text="{Binding ErrorMessage}" Foreground="Red" TextWrapping="Wrap"/>
Code-behind:
private void DatePicker_DateValidationError(object sender, DatePickerDateValidationErrorEventArgs e) { ErrorMessage = e.Exception.Message; } private void DatePicker_SelectedDateChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { ErrorMessage = ""; }