#155 – Implementing an Attached Dependency Property

When you implement a dependency property that will be used as a XAML attached property, you use the DependencyProperty.RegisterAttached method, rather than the DependencyProperty.Register method.  The signature of the RegisterAttached method, as well as all parameters, is identical to Register.

Below is an example, where we register the Person.AgeProperty, which we intend to use as a XAML attached property.

        static PropertyMetadata ageMetadata =
            new PropertyMetadata(0, null, new CoerceValueCallback(CoerceAge));

        public static readonly DependencyProperty AgeProperty =
            DependencyProperty.RegisterAttached("Age", typeof(int), typeof(Person), ageMetadata);

        public static void SetAge(DependencyObject depObj, int value)
        {
            depObj.SetValue(AgeProperty, value);
        }

Note that because we intend to use Age as an attached property, we must also implement the SetAge method.  (Standard CLR property wrapper is also required, but not shown).