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
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>, whereTis the desired type of your attached property (see Attached<T>).Mark your new property with the AttachedPropertyAttribute attribute.
Create a method that calls
SetValueon the attached property. This method must be namedSetX, whereXis 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