Converters–Part 0–My View on MVVM and Converters

Converters are a bit of a touchy subject in MVVM. Some would argue that the ViewModel is itself a “converter on steroids” and for the most part I agree, specifically when you are dealing with complex values (“I have an object of type Contract but I want to display a Customer on screen”). My view of MVVM is within view of the dogmatic MVVM, however I also have a strong pragmatic voice in my head telling me not to go overboard on things. So while I do think that a view model should closely resemble the data a view needs, I’m not of the opinion that it must match exactly.

The dogmatic view would mean that if a view needs a Foo formatted in a specific way as a string, then the view model should have a property on it that returns the Foo in that format. For example, if a view needs to display a decimal as a currency, it should have a string property that calls ToString(“C”) on the backing decimal (contrived example, and yes I’m aware of the format string in bindings as of Silverlight 4). I’ve never liked this approach – I would always prefer to have my view model have a decimal property and let the view format the decimal as needed. That’s the point of a view is it not? To format and display the data as needed? Similarly, there are times when I use a single property to power multiple items. For instance, I may have a drop down of choices bound to an enumeration property. At the same time each choice would have its own panel that shows or hides. Some would insist on one property for the drop down and one Visibility property for each of the panels. Personally, I would rather just bind the panels’ visibility directly to the same property as the drop down and use a converter to evaluate it to a Visibility.

For example, instead of this property:

I prefer this property:

To use the second property as the Visibility of a UIElement, I need a converter that is capable of converting a Boolean into a Visibility value. In my opinion, a ViewModel represents the data a view uses and a View should do any transformations necessary to use the data as it sees fit. While building complex Silverlight applications, I often find myself creating properties like the second one above and using them in more than one place on a View. I’m not a fan of inter-element binding when I already have a ViewModel property capable of handling it, so I frequently have situations like below:

For more information on converters, how they work, how to define them, etc., here are several links. For even more links, google has quite a few more.

Leave a Reply