Attached Properties VS Behaviors

One of the powerful concept of WPF is Attached Properties. The primary purpose of attached property is to define a unique value to child elements for a property, which is defined in Parent element as MSDN suggests. Some of the typical examples are Grid.Row, DockPanel.Dock, etc.

But it can also be used to attach additional information to an object, like Extension methods in C#. Examples are allowing an object to be draggable using Mouse, play music on some action, etc. I will take a simple piece of functionality to explain this. Let’s consider, we need to focus a control on loaded.

Using Attached Property

Usage in XAML

To make the work more systematic, Microsoft came up with an option called Behaviors. It offers more encapsulated way to extend functionality. There are some built-in behaviors shipped as part of Blend. Following code implements the same functionality using Behaviors.

Using Behaviors

Usage in XAML

There are some advantages and dis-advantages in both approach. Let me put it down to make the decision easier.

Event Handlers

Both scenario need an event subscription to the Control.Loaded event. In attached properties it is an ugly code, where we need to write extra plumbing to release those handlers. But behaviors offer a clean way to release event handlers – OnAttached and OnDetaching. If the functionality dealing with more event handling mechanisms, Behaviors are the best way.

Configuration in Style

For example, if you want to attach this piece of functionality to all the TextBoxes in your application, a global style would be the best option. But attached properties can be set in Style, where Behaviors cannot. This is also an important factor need to be considered before taking decision.

Casting

The PropertyChanged callback will give you the dependency object. This is the element in XAML, where we set the property. But to access some property or to invoke a method we need to cast it to UIElement or FrameworkElement. But in Behavior, it is possible to mention the datatype – Behavior. So no more casting. Using AssociateObject all the members of the type can be accessed. In above case, I mentioned it as FrameworkElement, since the Loaded event coming from that.

Visual Designer

Behaviors can be drag and drop into particular object using Blend, where Attached properties are not.You can drag and drop behavior objects on other behavior objects to set up a hierarchy, and you can set properties on objects already in the designer through the properties window.

Hope this will shed some light on choosing a right option.

Leave a comment

Up ↑