#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

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.

2 Responses to #122 – Validating a Dependency Property

  1. Pingback: #133 – Where a Dependency Property Gets Its Value « 2,000 Things You Should Know About WPF

  2. Pingback: #158 – When to Create a Custom Dependency Property « 2,000 Things You Should Know About WPF

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: