Converters–Part 1–Simple Code-behind Based Converter

Silverlight projects I’ve been a part of tend to develop a robust set of converters. Anything I can do to keep my view model in a relatively pure state (see Part 0 for more details) keeps me happy. However there are times when I also don’t want to write a converter for one simple “throw-away” data conversion. I know I’m not likely to reuse this and I know I also don’t want to change my view model for this one conversion either. Instead, I’ve been using a simple “Code behind converter” where you can specify your conversion code in the code behind of your view.

This converter simply provides a Convert and ConvertBack event that can be handled on the code behind.

For an example of it in use, here is a business entity (which has a status enumeration):

And here is a view model for a business view:

And here is the view that displays a friendly version of the status enumeration:

And here is the view’s code behind:

If it turns out you need this elsewhere, it’s easy to change this into its own converter because you followed the same approach as you would have when needing a converter in the first place. Move the code into a custom IValueConverter class and update your usages of this to your new converter.

Leave a Reply