nRoute - RelayConverters - Creation of local converters
2 minutes read
When developing Silverlight or WPF application we sometimes need de create converters that would be useful only in a particular view. We must then create a class and its corresponding file that will be completely useless for the rest of the application. On big projects it would lead to a huge number of converters.
The previous article was about RelayCommands, now we will see how nRoute helps in solving our problem by using RelayConverters.
RelayConverters follow the same principle as RelayCommands with a declaration of a relay in resource and an initialization done with a behavior. Enough talks, let’s code.
We will use a slightly modified version of the view models defined on the article about RelayCommands.
We want to display a list of book that changes following the number of people who liked the book. If we have more than 100 likes, we’ll say that a lot of people like this book. Under 100 likes we’ll say that not a lot of people likes it. And if we have no likes, guess what, no one likes it. Converters provides us with a way of doing that. But creating a class just for this is not of a big interest for the rest of the application. Therefore we will use a RelayConverter. Here is how to declare the Xaml :
As we can see, it really looks like the declaration of a RelayCommand. The only difference is that until now, we have declared the converter but not defined the method to use to convert. And for this, let’s go to the code-behind.
First we need to add a using :
This using gives us access to nRoute’s extension methods. One of them, SetRelayConverter, allows us to define the conversion method used by the RelayConverter. Here is how it is used :
SetRelayConverter is a generic function taking two typed parameters (input type parameter and output type parameter) and two parameters (the RelayConverter’s name and the conversion method to use). Finally, a little bit of code-behind for a strictly view issue, a class saved and yes it’s still MVVM.
As usual you can get the sources of the article on my skydrive.