Tuesday, 19 November 2013

Wpf Behavior in a Style

Often when using the MVVM design pattern we find ourselves writing custom Behaviors. These are little bits of code that could be written in the code behind. However by creating a behavior we have a reusable bit of code that can be added inline with Xaml. There are various reasons you might create a custom behavior but one typical example is a lack of dependency properties on some control you are using.

Lets take a concrete example, imagine you wanted to know the selected rows in a grid control and this control didn't expose such a dependency property. Well you could write a custom behavior something like below:-


As you can see this exposes an attached property called SelectedRows. We can now bind our view model to this like below:-


Now imagine you want something like this for every instance of GridControl because you have a generic view model which will bind to this property. Well you'd use a style of course...hmmm

It turns out that Behaviors does not have an accessible setter, see style error below:-


So how do we get around this limitation?
Well we create an attached property that holds a collection of Behaviors like so:-


We can then create a style for this like below. Notice our list of Behaviors is defined as x:Shared=False so each instance of this style will get its own collection.


No comments:

Post a Comment