#123 – Coercing a Dependency Property

A class that implements a dependency property can optionally provide a coercion callback, which it specifies when registering the property.  A coercion callback is called when a property is about to get a new value and gives the class a chance to coerce the property value to a different value.

You specify a validation callback when registering a dependency property, using the CoerceValueCallback delegate.

            PropertyMetadata ageMetadata =
                new PropertyMetadata(
                    18,     // Default value
                    new PropertyChangedCallback(OnAgeChanged),
                    new CoerceValueCallback(OnAgeCoerceValue));    // ** allow class to coerce value

            // Register the 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)

You might use coercion to enforce minimum and maximum values for a property.

        private static object OnAgeCoerceValue
            (DependencyObject depObj, object baseValue)
            int coercedValue = (int)baseValue;

            if ((int)baseValue > 120)
                coercedValue = 120;

            if ((int)baseValue < 1)
                coercedValue = 1;

            return coercedValue;