Fun with ValueConverters: building a Mustachify.me converter for Windows Phone & Windows 8

Valueconverters are a really usefull feature when you are building an app using the MVVM pattern so you can bind properties from your viewmodel of a specific type to a element in the view which can only bound to another type of object. Using avalueconverter you can convert the value of one kind of object to a different kind so you can still bind them.

What I often see when looking at code from people who are new to MVVM is that they have a lot of properties in their viewmodels that can easily be reduced by using valueconverters. The best example which is used the most is probably the Boolean to Visibility converter. When building an app, chances are high that you want to show or hide certain UI elements depending on some boolean in your viewmodel. To bad the Visibility property of these elements only wants a bind to the Visibility enum and not your boolean. By using a value converter you can switch this boolean value to a Visibility without creating a new Visibility typed property in your viewmodel that I see a lot of people doing.

Don’t worry you don’t have to create all these converters yourself. A lot of them are already created by others and shared on several locations. Microsoft made a coding4fun toolkit that contains the most important converters like the one i described above. You can check out these converters here: http://coding4fun.codeplex.com/wikipage?title=Converters

So how hard is it to create your own converter? It’s really easy and I’ll show it by creating a new converter step by step in the rest of this post. I was watching someone demoing a fun app a few weeks back that used the site http://Mustachify.me to add mustaches to pictures and i thought this could be a pretty cool converter to create and add to your application so you can change all your images in your apps to images with Mustaches.

To start let’s create a new Windows Phone 8 project (These valueconverters aren’t only for Windows Phone, you can also use them for Windows 8, WPF, Silverlight, etc) and we’ll choose the “Windows Phone Databound app” project template so we will get some out of the box simple MVVM implementation.

To make this as simple as possible let’s just open the MainViewModel.cs and remove the out of the box  LocalizedSampleProperty, the Items collection and the IsDataLoaded and LoadData methods. Now we only have a SampleProperty left and we’ll rename this to property to PhotoUrl and give it a default value of some random picture

   1: private string _photoUrl = "http://upload.wikimedia.org/wikipedia/commons/2/21/Steve_Ballmer_at_CES_2010_cropped.jpg";

   2: /// <summary>

   3: /// Sample ViewModel property; this property is used in the view to display its value using a Binding

   4: /// </summary>

   5: /// <returns></returns>

   6: public string PhotoUrl

   7: {

   8:     get

   9:     {

  10:         return _photoUrl;

  11:     }

  12:     set

  13:     {

  14:         if (value != _photoUrl)

  15:         {

  16:             _photoUrl = value;

  17:             NotifyPropertyChanged("PhotoUrl");

  18:         }

  19:     }

  20: }

Our simple viewmodel is ready so now lets create the UI for this example. Just remove everything inside the LayoutRoot Grid and place a new Pivot there with 2 pivot items. inside the pivot items we’ll place 2 images. 1 original and 1 with the added mustaches.

   1: <phone:Pivot Title="mustachifymeconverter" Grid.Row="1">

   2:     <phone:PivotItem Header="default">

   3:         <Grid>

   4:             <Image Source="{Binding PhotoUrl}"/>

   5:         </Grid>

   6:     </phone:PivotItem>

   7:     <phone:PivotItem Header="mustache">

   8:         <Grid>

   9:             <Image Source="{Binding PhotoUrl}"/>

  10:         </Grid>

  11:     </phone:PivotItem>

  12: </phone:Pivot>

Since we haven’t implemented the valueconverter yet the app will now show just 2 images both bound to the same PhotoUrl property created in the viewmodel. To make our example build we’ll have to remove the MainLongListSelector_SelectionChanged and the OnNavigatedTo methods from the MainPage.xaml.cs and the code inside the Application_Activated method in the App.xaml.cs since these are not needed anymore.

Let’s run the app and see if everything is working. The app should look something like this, showing a picture of Steve without any mustache :)

mustachedemo1   

It’s time to add the MustachifyMeConverter to our project. Just create a new class called MustachifyMeConverter and make it implement :IValueConverter

   1: public class MustachifyMeConverter : IValueConverter

   2: {

   3:     public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

   4:     {

   5:         throw new NotImplementedException();

   6:     }

   7:  

   8:     public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

   9:     {

  10:         throw new NotImplementedException();

  11:     }

  12: }

When you implement the IValueConverter you’ll have to implement 2 methods. Convert and ConvertBack. Since http://Mustachify.me only supports adding mustaches we’ll leave the ConvertBack as it is and only implement Convert.

Implementing the Mustachify.me converter Convert method is really simple. you actually only need 1 line of code: check if the string passed as a value is empty, if not just add “http://mustachify.me/?src=” in front of the old url and return it.

   1: public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

   2: {

   3:     return value != null ? "http://mustachify.me/?src=" + value.ToString() : string.Empty;

   4: }

Yes ValueConverters are really easy to create so let’s also use it in our app. Adding it to the XAML is also pretty easy. Since building the UI should be done in Blend (in my opinion) lets add the value converter in Blend! Fire up the Mainpage in Blend and select the image on the 2nd pivot page. In the properties window select the Source and choose “Create Data Binding”. In the popup you’ll see an option to select a ValueConverter on the left bottom of the window.

mustachedemo2

Press “Add value connector” and in the new window select the MustachifyMeConverter we created. Press Ok and we’re all done.

mustachedemo3

Fire up the app again and now the 2nd pivot item should have mustaches added to the picture without adding any code in our viewmodel to support this.

mustachedemo1mustachedemo4

Hopefully this small tutorial gave you some ideas on how and when to use ValueConverters when building Windows Phone apps or any other XAML based apps using the MVVM pattern.

You can download the sample project here: http://sdrv.ms/VYhVVk

Happy coding!

Geert van der Cruijsen

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter

Comments are closed.