Adventures in MVVM – Generalized Command Behavior Attachments

There are several examples on the web that describe the “Attached Behavior” pattern in Silverlight and WPF. This pattern works really well for binding commands in the ViewModel to controls in the View. The problem with this is that for every behavior, there is a LOT of boilerplate code that goes along with it. Because the DepencencyProperties need to be static, they cannot be easily abstracted into a common class.

If you want to attach a MouseEnterBehavior to a control, you need to create two or three static Dependency Properties in the MouseEnter class. They are MouseEnter.Command, MouseEnter.MouseEnterBehavior and optionally, MouseEnter.CommandParameter.

This is a classic case of reuse via “Copy and Paste”. The problem is that there are several places in this code where you need to change three different types and many strings. If you don’t invoke the magic incantation properly, nothing works. It will compile but it won’t work (or you will get an obscure XAML parse error).

I cringe whenever I have to employ copy/paste reuse. In the cases where it is absolutely necessary (such as this), I believe the risk can be reduced proportionately to the complexity of the modification after you paste. This is why I came up with an Attachment base class to generalize all of this boilerplate code. The previous code can be reduced to:

In addition to the decreased configuration complexity, the actual code that needs to be copied goes from 58 lines of boilerplate code to 11 lines of boilerplate code. This is a big win, in my opinion.

In this code, I am using the CommandBehaviorBase class from the Prism framework. It is part of the generic constraints. If you use something else for your behaviors, replace it as you see fit. Your own base class for command behaviors would slip in nicely, I am sure.

This entry was posted
on Saturday, August 22nd, 2009 at 1:45 am and is filed under Uncategorized.
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.