#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 =
                    "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