#574 – Complete Example of Implementing a Dependency Property

Recall that you can implement a dependency property if your class inherits from DependencyObject.  Here is a complete example, showing how to implement a dependency property.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;   // Remember to reference WindowsBase

namespace PersonDLL
{
    public class Person : DependencyObject
    {
        // Classic CLR properties
        public string Name { get; set; }
        public bool AARPCandidate { get; set; }

        // Age is a dependency property
        public static readonly DependencyProperty AgeProperty;

        // Call methods in DependencyObject to read/write property values
        public int Age
        {
            get { return (int)GetValue(AgeProperty); }
            set { SetValue(AgeProperty, value); }
        }

        // Static constructor sets everything up
        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)
        }

        // Value has changed
        private static void OnAgeChanged
            (DependencyObject depObj, DependencyPropertyChangedEventArgs e)
        {
            Person p = (Person)depObj;
            p.AARPCandidate = (int)e.NewValue > 60 ? true : false;
        }

        // Allow coercing value being set
        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;
        }

        // Validate a value beint set
        private static bool OnAgeValidateValue(object value)
        {
            int age = (int)value;

            // Only allow reasonable ages
            return (age > 0) && (age < 120);
        }
    }
}