Universal Windows Dev

How to: Implementing ValueConverters in your Windows Store apps

By 19th April 2013 3 Comments

I don’t know how it has taken so long to come across value converters but yesterday while I was redesigning the user interface for The Hullfire application for Windows Phone I read about value converters. I thought that this would be a great idea to implement into my code as I was manually assigning random number intervals to my tiles in the application to update.

The Hullfire Tiles

Category Tiles for The Hullfire Windows Phone App

To create a converter, you will want to go ahead and create a new class for your converter. Give it a sensible name. For my example, I named my converter “RandomTimeSpanGenerator”. You will want to make your class public, reference “System.Windows.Data” and inherit “IValueConverter”.

You should now have a class file that looks like this:

using System;
using System.Windows.Data;

namespace App.Converters
{
    public class RandomTimeSpanGenerator : IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }
    }
}
Now for what I wanted to do, create a random timespan generator, I needed to create a random number generator and then return a timespan value in the Convert method. I don’t need to ever convert back from this so this method can be left as is.

My final result for the class is as follows:

using System;
using System.Windows.Data;

namespace App.Converters
{
    public class RandomTimeSpanGenerator : IValueConverter
    {
        readonly Random _generator = new Random();

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return TimeSpan.FromSeconds(_generator.Next(2, 5));
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }
    }
}
Now that you have a converter you can bind a property to a XAML element and use the converter to convert that value. In my example above, I’m not really converting and more just creating a value for the binding but this makes it easier when you are binding to templates which don’t give you access to the name of a XAML element.

So now we want to reference your converter in the resources for the page you are going to use it in. Open up your XAML page which you are going to be using the converter on. In the initial tag of your page (should be ), add the following xmlns value:

xmlns:local="clr-namespace:App.Converters"
The namespace should be the namespace in the value converter class. Now in your LayoutRoot Grid element, add the following tags:
<grid .Resources>
            <local:randomtimespangenerator x:Key="TimeSpanGenerator"></local:randomtimespangenerator>
            <local:optiontobrushconverter x:Key="OptionToBrushConverter"></local:optiontobrushconverter>
</grid>

Here you must assign your class in the form “local:classname” and the key is a value that you can pick. It is the key that you will use to reference the resource. Now you are ready to use your value converter on your binding value. Here is my example:
<telerikprimitives:radslidehubtile Title="{Binding Title}"
                                                             FontSize="{StaticResource PhoneFontSizeMedium}"
                                                             FontFamily="{StaticResource PhoneFontFamilyLight}"
                                                             Width="400"
                                                             Height="195"
                                                             Padding="8"
                                                             UpdateInterval="{Binding Interval, Converter={StaticResource TimeSpanGenerator}}"
                                                             telerikPrimitives:RadHubTileService.GroupTag="SlideTile"
                                                             telerikCore:InteractionEffectManager.IsInteractionEnabled="true"
                                                             Background="{Binding Category, Converter={StaticResource OptionToBrushConverter}}">
</telerikprimitives:radslidehubtile>
In the case of my generator, the Interval value is irrelevant as it isn’t being converted, however you may notice that I have used another value converter on the Background property. This does in fact convert the value of the Category to a SolidColorBrush.

Here is the value converter for using the Category value to bind a SolidColorBrush to the background property:

using System;
using System.Windows.Data;
using System.Windows.Media;

namespace TheHullfire_WP8.Converters
{
    public class OptionToBrushConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if ((string) value == "Life")
            {
                return new SolidColorBrush(Color.FromArgb(255, 180, 147, 164));
            }

            if ((string) value == "Music")
            {
                return new SolidColorBrush(Color.FromArgb(255, 204, 51, 63));
            }

            if ((string) value == "Arts")
            {
                return new SolidColorBrush(Color.FromArgb(255, 106, 75, 61));
            }

            if ((string) value == "Sport")
            {
                return new SolidColorBrush(Color.FromArgb(255, 88, 161, 83));
            }

            if ((string) value == "Fashion")
            {
                return new SolidColorBrush(Color.FromArgb(255, 113, 96, 168));
            }

            if ((string) value == "Tech")
            {
                return new SolidColorBrush(Color.FromArgb(255, 63, 159, 217));
            }

            return new SolidColorBrush(Color.FromArgb(255, 235, 103, 44));
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }
    }
}
I hope that you may have found this useful and maybe you will find some cool ways of implementing converters into your Windows Phone applications. Let me know if there are ways that I can improve on using converters in my applications. As I stated before, I have only just had a go at using them and it would be great to get some helpful hints and tips from you to share with everyone in the comments section below.

Author James Croft

James is a .NET developer for Black Marble Ltd. with over 5 years app development experience in Microsoft platforms. He enjoys blogging, helping others learn to code, making YouTube videos, spending time with his girlfriend but most of all, penguins.

More posts by James Croft

Join the discussion 3 Comments

  • Andreas says:

    Thanks for the guide, didn’t find the -tag and the import tag in the xaml header anywhere else so this one helped me!

  • D says:

    Rather than doing all those casts in that Convert method, you can simply declare:

    string stringValue = value as string;

    so it saves on casting the value constantly as it goes down your if statements.

Leave a comment