#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);

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

3 Responses to #98 – How Attached Properties Work in WPF

  1. Rob Relyea says:

    Sean-
    DependencyProperties are a WPF concept, not a XAML concept.
    XAML’s attached properties are only based on the static setter and getter methods. Storage is up to the implementation of those methods.

    Many use DependencyProperties. In .NET 4, non WPF uses can also use AttachablePropertyServices.

    Saving object graphs to XAML via XamlWriter.Save or XamlServices.Save does require that the attached property be backed by a dependencyproperty (when using XamlWriter.Save) or AttachablePropertyServices (when using XamlServices.Save).

    Thanks, Rob

    • Sean says:

      Thanks Rob, I was a little muddy on the implementation of attached properties, not realizing that they aren’t always persisted using dependency properties. Your explanation helps. I updated the post, hopefully a bit more accurate now and possibly a bit more clear. (Also trying to stay withing 150 words, which is sort of my arbitrarily imposed “bite-sized chunk” limit).

      Thanks again for the comments and explanation–I very much appreciate it.

      Sean

  2. Pingback: Day #1: Introduction to XAML Part II | Thirty Days of WPF

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: