#1,039 – Intercepting Bad Date Strings Entered into a DatePicker

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

1039-001
1039-002

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #1,039 – Intercepting Bad Date Strings Entered into a DatePicker

  1. Pingback: Dew Drop – March 28, 2014 (#1753) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: