PostSharp6.8//XAML/Attached Property

Attached Property

In XAML, Attached properties are a special kind of properties that are settable on a different object than the one that exposes it. An example of attached property is DockPanel.Dock. Attached properties are a special kind of dependency properties and thus require the same amount of boilerplate code to be written.

The AttachedPropertyAttribute aspect allows you to automate the implementation of attached properties in your classes and eliminates the boilerplate.

This topic contains the following sections:

The AttachedPropertyAttribute aspect is a special case of the DependencyPropertyAttribute aspect. Therefore you can refer to the Dependency Property article for additional documentation on topics such as validation, property change callbacks, and naming conventions.

Creating a simple attached property

To add a new attached property to your class

  1. Add a new static property to your class with a chosen name, a public getter and private setter. Declare the property type as Attached<T> where T is the desired type of your attached property (see Attached<T>).

  2. Mark your new property with the AttachedPropertyAttribute attribute.

  3. Create a method which calls SetValue on the attached property. This method must be named SetX, where X is the name of the attached property and must look as follows:

    C#
    [public static void SetDock(DependencyObject host, string value) => Dock.SetValue(host, value);
    Note Note

    Why can't PostSharp create the "Set" method boilerplate automatically? It's because PostSharp runs after compilation, but this code must already exist prior to XAML compilation.

C#
[AttachedProperty]
public static Attached<Dock> Dock { get; set; }
public static void SetDock(DependencyObject host, string value) => Dock.SetValue(host, value);
Using the dependency property

After you have marked your property with the AttachedPropertyAttribute attribute, you can directly start to use it in XAML. For example, you can set the value of the property on any object using the attached property syntax in XAML.

XAML
<MyDockPanel>
  <CheckBox MyDockPanel.Dock="Top">Hello</CheckBox>
</MyDockPanel>

You can also read and write the property value on any object in C# by using the Attached<T>.GetValue(DependencyObject) and Attached<T>.SetValue(DependencyObject, T) methods.

C#
MyDockPanel.Dock.SetValue(this.HelloCheckBox, Dock.Top);

To get a DependencyProperty instance that is backing your attached property, read the value of the Attached<T>.RuntimeProperty property.

C#
MyDockPanel.Dock.RuntimeProperty.OverrideMetadata( typeof(MyPropertiesListView), new PropertyMetadata(Dock.Right) ));
See Also