#117 – Registering a Dependency Property

To implement a dependency property, a class will create a single static instance of the DependencyProperty class.  This instance is static because DependencyProperty just describes the dependency property, rather than being a place to store the actual property value.

You start by declaring a static member for the new property.

        public static readonly DependencyProperty AgeProperty;

You typically register the property in a static constructor, using the static DependencyProperty.Register method.

        static Person()
        {
            PropertyMetadata ageMetadata =
                new PropertyMetadata(
                    18,     // Default value
                    new PropertyChangedCallback(OnAgeChanged),
                    new CoerceValueCallback(OnAgeCoerceValue));

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

The first three parameters passed to Register are required.

You can also specify:

  • A default value for the property
  • A method to be called when the property value changes
  • Coercion and validation callbacks

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 #117 – Registering a Dependency Property

  1. Pingback: #154 – Reusing an Existing Dependency Property in Your Class « 2,000 Things You Should Know About WPF

  2. Pingback: #155 – Implementing an Attached 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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 131 other followers