The Attached Behavior pattern

My favorite feature of WPF (desktop and web versions) is attached properties.  It would be good enough if attached properties merely enabled things like keeping layout properties (Canvas.Left) organized by the type of container rather than the type of content, but they also enable a great little design pattern:  Attached Behavior.

Nikhil recently blogged about behaviors in terms of Silverlight (, but of course the same technique is available in desktop WPF and we widely used it during Expression development.  Nikhil describes the technique well, but let me reiterate in Design Patternese:

The Attached Behavior pattern encapsulates "behavior" (usually user interactivity) into a class outside the visual heirarchy and allows it to be applied to a visual element by setting an attached property and hooking various events on the visual element.

One of the first behaviors we wrote in Blend was the ClickBehavior.  The M-V-VM pattern uses Commands instead of events in many cases, but WPF controls don't trigger Commands in all the interesting cases.  Button for example has a Command property, but it only fires when the Button is clicked, not double-clicked or right-clicked.  ClickBehavior defines attached properties like DoubleClickCommand of type Command.  When you set these properties the behavior registers for the MouseRightButtonUp event and in the handler for that event invokes the Command in the DoubleClickCommand behavior.  Interestingly, this same behavior can be used to attach Commands to *any* UIElement, even a rectangle.  This turns out to be useful for adding interactivity to parts of the UI without the extra cost of a full-blown Control. 

You can do a lot with the Attached Behavior pattern.  Drag and drop is an obvious candidate for a behavior.  A single DragDropBehavior class can register for all the basic input events and invoke Commands like OnDrop and OnDrag, allowing you to make any visual a DropTarget or DropSource without sub-classing or adding substantial code to your page.  As I mentioned in my previous post, Silverlight's Parts and States model does not work easily with the built-in desktop WPF controls because those controls do not trigger the state changes.  An attached behavior can hook the right events and do the state transitions...the first prototype of the Silverlight model was written in desktop WPF as an attached behavior. 

More on this pattern later.