Open sandboxFocusImprove this doc

Attached Property

In XAML, attached properties are a special kind of properties that you can set on a different object than the one that exposes them. An example of an 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.

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

Adding an attached property to your class

  1. Add a new static property to your class with a chosen name, a public getter, and a 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 that 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:

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

    PostSharp cannot create the "Set" method boilerplate automatically because PostSharp runs after compilation, but this code must already exist before XAML compilation.

Example

The following example declares a Dock attached property in the MyDockPanel class:

[AttachedProperty]
public static Attached<Dock> Dock { get; private set; }

public static void SetDock(DependencyObject host, Dock value) => Dock.SetValue(host, value);

Using the attached 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.

<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 GetValue(DependencyObject) and SetValue(DependencyObject, T) methods.

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

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

MyDockPanel.Dock.RuntimeProperty.OverrideMetadata( typeof(MyPropertiesListView), new PropertyMetadata(Dock.Right) );

See Also

Reference

AttachedPropertyAttribute
DependencyPropertyAttribute
DependencyProperty
Attached<T>
GetValue(DependencyObject)
SetValue(DependencyObject, T)
RuntimeProperty

Other Resources

Attached Properties Overview
Dependency Property