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

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;
        }
About these ads

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 #123 – Coercing a Dependency Property

  1. Pingback: #133 – Where a Dependency Property Gets Its Value « 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

Follow

Get every new post delivered to your Inbox.

Join 351 other followers

%d bloggers like this: