This is the online documentation for PostSharp 5.0.
Download PDF or CHM. Go to v4.3 or v5.0

Attached Property

Attached properties are a special kind of properties defined by XAML that are settable on any object. Attached properties are typically implemented as dependency properties and thus require the same amount of boilerplate code to be written. PostSharp allows you to automate the implementation of attached properties in your classes and eliminates the boilerplate.

The AttachedPropertyAttribute aspect is basically a special case of the DependencyPropertyAttribute aspect, and both aspects share the same set of features. Therefore you can refer to the Dependency Property article for additional documentation on topics such as validation, property change callbacks, member names customization etc.

This topic contains the following sections:

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 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.

Declaring a new attached property
public static Attached<Dock> Dock { get; set; }
Using the dependency property

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

Setting the attached property value in XAML
  <CheckBox MyDockPanel.Dock="Top">Hello</CheckBox>

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

Setting the attached property value in C#
MyDockPanel.Dock.SetValue(this.HelloCheckBox, Dock.Top);

If you want to manipulate the attached property using the WPF property system API, then you need to acquire a corresponding instance of the DependencyProperty class. To get a DependencyProperty instance that is backing your attached property, read the value of the RuntimeProperty property of the Attached<T> class.

Overriding the default value of the attached property
MyDockPanel.Dock.RuntimeProperty.OverrideMetadata( typeof(MyPropertiesListView), new PropertyMetadata(Dock.Right) ));
See Also