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