#98 – How Attached Properties Work in WPF

Attached properties in XAML allow attaching a property value to an object that is of a different type than the type where the property is defined.  (E.g. Grid.Row property can be set for a Button).

When the XAML parser encounters an attached property, it calls a static method on the class where the property is defined.  So setting a value for Grid.Row on a Button is equivalent to:

 Grid.SetRow(myButton, 1);

In WPF, attached properties are often implemented using dependency properties.  The object on which the property is being set (e.g. Button) inherits from DependencyObject, which means that it can store a collection of dependency properties.

When dependency properties are used for storing the values of attached properties, the static setter method in turn just calls the SetValue method on the object passed in to it.  So the method listed above would be implemented as:

 myButton.SetValue(Grid.RowProperty, 1);

#97 – Attached Properties

In XAML, attribute syntax is normally used to set the value of a property on an object.  But through the use of attached properties, you can set a value for a property that comes from another object.

Attached property syntax follows the form TypeName.PropertyName, where the type named is the type where the property is defined.

In the example below, we have two Button controls contained in a grid.  To indicate their position in the grid, we specify Grid.Row and Grid.Column properties for each.  The buttons don’t have Row and Column properties and neither does the Grid .  But the Grid does have Row and Column as attached properties–meaning that it can apply the properties to other objects, indicating where those objects should appear in the grid.

     <Button Grid.Row="1" Grid.Column="0" Content="Dee" Height="23" Name="button1" Width="75" />
     <Button Grid.Row="1" Grid.Column="1" Content="Dum" Height="23" Name="button2" Width="75" />