Post­Sharp Documentation / 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.

C#
[AttachedProperty]
public static Attached<Dock> Dock { get; set; }
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.GetValue(DependencyObject) and Attached.SetValue(DependencyObject, UTP) 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