#1,141 – Attached Properties Allow Customization of Existing Controls

An attached property is a dependency property defined in one class and then attached (used) on an instance of some other class.

You can define your own attached properties as a mechanism for extending the appearance or behavior of a control.

Below, we register a dependency property of type bool, named Important.  When Important is set to true, we set the foreground brush of the control to red.

    public class MyAttProps
    {
        // Surround property definition
        static PropertyMetadata ImportantMetadata =
            new PropertyMetadata(
                false,                // Default value
                OnImportantChanged,   // Changed callback
                null);                // Coerce value callback

        public static readonly DependencyProperty ImportantProperty =
            DependencyProperty.RegisterAttached(
                "Important",          // Property name
                typeof(bool),         // Property type
                typeof(MyAttProps),   // Defining class type
                ImportantMetadata);   // Metadata described above

        // Allow setting value from XAML
        public static void SetImportant(DependencyObject depObj, bool value)
        {
            depObj.SetValue(ImportantProperty, value);
        }

        public static bool GetImportant(DependencyObject depObj)
        {
            return (bool)depObj.GetValue(ImportantProperty);
        }

        // Important property has changed
        public static void OnImportantChanged(
            DependencyObject d,
            DependencyPropertyChangedEventArgs e)
        {
            Control ctrl = d as Control;
            bool important = (bool)e.NewValue;
            if ((ctrl != null) && important)
                ctrl.SetValue(Control.ForegroundProperty, Brushes.Red);
            else
                ctrl.ClearValue(Control.ForegroundProperty);
        }
    }

We can now use this new property from XAML:

        <Label x:Name="lblHi" Content="Hi there" 
               loc:MyAttProps.Important="True"
               Background="AliceBlue"/>

1141-001