#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

Advertisement

#638 – PreviewTextInput Is Not Fired In Many Cases

You’d normally use the PreviewTextInput event to filter data being entered into a text-based control like the TextBox.  But the PreviewTextInput event is fired for text that is being added to the control, but not fired for certain keypresses that could also result in changes to the text.

Key presses that do not result in the PreviewTextInput event being fired include:

  • Spacebar
  • Backspace
  • Home/End/Delete/Insert keys
  • Arrow keys
  • Control key combinations, including Ctrl+V

This means that if you were only validating text input in PreviewTextInput, a user could use Ctrl+V to do a paste operation into a TextBox and you wouldn’t get a chance to validate the text being added.

All of these key press do result in the PreviewKeyDown event being fired.  This means that to do complete validation of all changes to a TextBox, you’ll likely want to do some validation in PreviewTextInput and some additional validation in PreviewKeyDown.

#122 – Validating a Dependency Property

A class that implements a dependency property can optionally provide a validation callback, which it specifies when registering the property.  A validation callback is called when a property is about to be set to a new value and returns true or false, indicating whether the new value is valid.

You specify a validation callback when registering a dependency property.

            AgeProperty =
                DependencyProperty.Register(
                    "Age",                 // Property's name
                    typeof(int),           // Property's type
                    typeof(Person),        // Defining class' type
                    ageMetadata,           // Defines default value & changed/coercion callbacks  (optional)
                    new ValidateValueCallback(OnAgeValidateValue));   // *** validation (optional)

The validation callback has the new value passed in.

        private static bool OnAgeValidateValue (object value)
        {
            int age = (int) value;

            // Only allow reasonable ages
            return (age > 0) && (age < 120);
        }

If the property is being set to an invalid value, an exception is thrown.

            Person p = new Person("Samuel", "Clemens");
            p.Age = 40;     // ok
            p.Age = 300;    // throws System.ArgumentException