Click here to Skip to main content
15,880,972 members
Articles / Mobile Apps

Use Converters in your Windows Phone Apps

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
12 Apr 2014CPOL10 min read 9.6K   1  
In a recent post I have covered several approaches to store data in a Windows Phone application. Another important problem is presenting data in an easy and controllable way that would not interfere with other layers of your app.
In a recent post I have covered several approaches to store data in a Windows Phone application. Another important problem is presenting data in an easy and controllable way that would not interfere with other layers of your app. To some extent XAML handles this task well, but from time to time just markup is not enough and one needs to introduce a portion of imperative code to present data nicely. To make this possible each binding in a XAML-based app may specify a converter, which will be responsible for transforming data between internal and external representations.

The key purpose of data converters is to allow for making an application appealing and intuitive without cluttering XAML significantly or, what is much worse, mixing presentation logic into the model layer. Converters are called by the Data Binding mechanism whenever binding actually occurs (for example, when a control is notified about the change in the underlying property). In many cases a converter is used even if you don’t specify any in the controls’ markup – a common example is the following line:<o:p>

<Image Source="/Assets/Amazing.png" />

If you peek into the declaration of the Source property, you will notice that its type is actually ImageSource – not a string, which means that the file path should be transformed into a suitable object. This is done behind the curtains by the built-in ImageSourceConverter class, which is implicitly used by the Image control. This way converters allow us to specify a natural value in XAML and have it transformed into something suitable for the particular property of a control. While there is a range of built-in converter classes, the mechanism is so flexible and easy to use that you will likely want to introduce your own converters – that’s what we will discuss here.

Let us start with an example, which might be quite useful in real applications despite its stunning simplicity. Suppose that in your model you have a property that should be either visible to users or hidden from them depending on some flag::<o:p>

class BooleanToVisibilityViewModel <br />    : INotifyPropertyChanged<br />{<br />  private bool _allowEdit;<br />  public bool AllowEdit<br />  {<br />    get { return _allowEdit; }<br />    set<br />    {<br />      _allowEdit = value;<br />      OnPropertyChanged("AllowEdit");<br />    }<br />  }<br /><br />  private string _text;<br />  public string Text<br />  {<br />    get { return _text; }<br />    set<br />    {<br />      _text = value;<br />      OnPropertyChanged("Text");<br />    }<br />  }<br /><br /><br />  #region INotifyPropertyChanged<br />  public event PropertyChangedEventHandler PropertyChanged;<br /><br />  protected void OnPropertyChanged(string propName)<br />  {<br />    if (PropertyChanged != null)<br />    {<br />      PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propName));<br />    }<br />  }<br />  #endregion<br />}<br />

The first thing that one might give a try here is to bind Visibility of a control directly to the AllowEdit property:<o:p>

<TextBox x:Name="text" Text="{Binding Text, Mode=TwoWay}"<br />     Visibility="{Binding AllowEdit}" /><br />

Unfortunately, this is not going to work because the type of the Visibility property does not match the type of AllowEdit. The naive approach suggests that there is no better way to accomplish what we want than to introduce something like a TextVisible property in the model class and bind visibility to it:<o:p>

public Visibility TextVisible<br />{<br />  get<br />  {<br />    return AllowEdit ? Visibility.Visible : Visibility.Collapsed;<br />  }<br />}<br />
<TextBox x:Name="text" Text="{Binding Text, Mode=TwoWay}"<br />     Visibility="{Binding TextVisible}" /><br />

Even though this code will compile, run and produce the desired result it actually looks like a much more severe failure than the last one because we have just pulled pure presentation stuff into the model class. This not only means writing and maintaining more non-reusable code but also makes the class less portable. What we want instead is to bind directly to the AllowEdit property and provide the framework with a clue on how to get Visibility from a bool. Enter the converter:<o:p>

public class BooleanToVisibilityConverter : IValueConverter<br />{<br />  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)<br />  {<br />    bool isVisible = (bool)value;<br />    return isVisible ? Visibility.Visible : Visibility.Collapsed;<br />  }<br /><br />  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)<br />  {<br />    return (Visibility)value == Visibility.Visible;<br />  }<br />}<br />

The only requirement that a class must satisfy to be used as a converter is to implement the IValueConverter interface. There are only two methods to implement: Convert and ConvertBack, and when you use OneWay binding it is just OK to leave the latter without any implementation. As you can see, the bool-Visibility converter is very simple and does not differ much from the TextVisible property that we have seen before. The next question is how to use it?<o:p>

First, we need a way to refer to the class in the markup – for this purpose we introduce a StaticResource - for example, in the application’s resources section:

<!-- In App.xaml --><br /><Application.Resources><br />  <local:LocalizedStrings x:Key="LocalizedStrings"/><br />  <local:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/><br />  <!-- other resources --><br /></Application.Resources><br />

Now, when the converter got its XAML name we only need to tell the binding to use it:<o:p>

<CheckBox x:Name="allowEdit" <br />  IsChecked="{Binding AllowEdit, Mode=TwoWay}" <br />  Content="allow edit" /><br /><TextBox x:Name="text" <br />  Text="{Binding Text, Mode=TwoWay}"<br />  Visibility="{Binding AllowEdit, Converter={StaticResource BooleanToVisibilityConverter}}" /><br />

This is actually all that you have to do to make the text box disappear when the AllowEdit flag is set to false and become visible when it’s true. Even though we have written a bit more code than with an additional property in the model class, the approach with data converter has at least two significant advantages. First, it does not prompt us to change the model class in any way – every piece of new logic goes directly in the presentation layer. Besides, once you have implemented a converter and added a resource for it, you can reuse it anywhere in your application at no cost at all. To get these advantages you need to go through three simple steps:
  1. Implement the IValueConverter interface in the converter class,
  2. Create a StaticResource for this class that you use in XAML,
  3.  Refer to this resource to specify a converter in controls’ Binding.

Precisely as you would expect one is not limited to simple types when data converters are concerned. That said, you can transform anything you want into whatever the controls can consume: visibility, colors, brushes, styles, images, strings and so on. Let us take another example and introduce the Task class:

public class Task : INotifyPropertyChanged<br />{<br />  public string Title { get; set; }<br /><br />  private int _priority;<br />  public int Priority<br />  {<br />    get { return _priority; }<br />    set<br />    {<br />      _priority = value;<br />      OnPropertyChanged("Priority");<br />    }<br />  }<br /><br />  #region INotifyPropertyChanged<br />  public event PropertyChangedEventHandler PropertyChanged;<br /><br />  protected void OnPropertyChanged(string propName)<br />  {<br />    if (PropertyChanged != null)<br />    {<br />      PropertyChanged.Invoke(<br />        this,<br />        new PropertyChangedEventArgs(propName));<br />    }<br />  }<br />  #endregion<br />}<br />

Completing tasks is impossible without proper prioritization – that’s why we have the Priority property in the class. Priority of any particular task must be clear to user and the higher it is the more attention it should draw. Mere numbers can’t communicate the importance of tasks, so we will use a clever color scheme. For this purpose, we need a converter capable of transforming integer values from 0 to 2 into colors, which would make it clear that 0 is the lowest priority, while 2 is the hottest thing that should be addressed as soon as possible:<o:p>

public class PriorityToBrushConverter : IValueConverter<br />{<br />  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)<br />  {<br />    var priority = (int)value;<br />    switch (priority)<br />    {<br />      case 0:<br />        return new SolidColorBrush(Colors.Green);<br />      case 1:<br />        return new SolidColorBrush(Colors.Yellow);<br />      case 2:<br />        return new SolidColorBrush(Colors.Red);<br />      default:<br />        return new SolidColorBrush(Colors.Black);<br />    }<br />  }<br /><br />  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)<br />  {<br />    throw new NotImplementedException();<br />  }<br />}<br />

Note that the converter doesn’t actually return Color instances – Brush class is used instead. The reason is that we are going to pass the values to the Fill property, whose type is Brush. If you accidentally pass Color where Brush is expected, you might end up with an undecipherable runtime error, so pay close attention to the things of this kind. With the converter in place, we simply define a resource for it and consume it in the binding:<o:p>

<!-- in App.xaml --><br /><Application.Resources><br />  <local:PriorityToBrushConverter x:Key="PriorityToBrushConverter"/><br />  <!-- other resources --><br /></Application.Resources><br /><br /><!-- in Page.xaml --><br /><StackPanel><br />  <Rectangle x:Name="PriorityColor" <br />    Fill="{Binding Priority, Converter={StaticResource PriorityToBrushConverter}}"<br />    Width="200" Height="50" /><br />  <TextBox x:Name="TitleBox" <br />    Text="{Binding Title, Mode=TwoWay}" /><br />  <Slider Minimum="0" Maximum="2" <br />    Value="{Binding Priority, Mode=TwoWay}" /><br /></StackPanel><br />

If you launch this on a Windows Phone, you should see a picture like this:<o:p>


SolidColorBrush is a full-blown presentation class, whose only name suggests that there is little room for it in the model layer. If this is not convincing, imagine that the choice of colors might depend on the current theme or any other piece of the application’s state, which means a lot more dependencies for the model. Any idea how would one test Task class if at some point it wants to peek into the Application to know if user likes light or dark theme or what is their current accent color?<o:p>

Another inherently presentational concept are resource strings, which give us an easy way to localize applications and make them available to wider range of users. Resources are hardly welcomed guests in the model layer, but you will definitely want to use them to present your objects. Let us look how converters might help here. Suppose, we have a collection of some items identified with a Kind property – a string (it could be an enumeration, integer or a GUID – for now it doesn’t matter.) What does matter is that the descriptions of items, which we want to be visible to users, are stored in the resource dictionary and depend solely on the Kind. This indicates that we don’t need to store descriptions in the Task class – it would mean a degree of duplication – and can use a converter to fetch them instead:<o:p>

public class Item<br />{<br />  public string Kind { get; set; }<br />}<br /><br />public class ItemToDescriptionConverter : IValueConverter<br />{<br />  private const string _DescriptonKeyFormat = "ItemDescription_{0}";<br /><br />  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)<br />  {<br />    var item = (Models.Item)value;<br />    var resourceKey = String.Format(_DescriptonKeyFormat, item.Kind);<br />    return AppResources.ResourceManager.GetString(resourceKey, culture);<br />  }<br /><br />  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)<br />  {<br />    throw new NotImplementedException();<br />  }<br />}<br />

Here I assume that converter gets the entire Item object – not just its Kind – to demonstrate that there are little limitations in what you can bind controls to. Such a thing could be helpful in case the displayed description depends on some other properties of the Item – for instance, you might want to insert certain numbers into the string. In this example we just take the Kind property of the Item argument and use it to retrieve the corresponding resource string from the application’s dictionary. To extract the resource we use an instance of the ResourceManager class, which can be accessed through the AppResources class kindly generated by Visual Studio from the .resx dictionary. The only thing left is to actually utilize the converter in XAML – as usual, we declare the corresponding StaticResource and mention it in the control’s Binding:

<!-- in App.xaml --><br /><Application.Resources><br />  <local:ItemToDescriptionConverter x:Key="ItemToDescriptionConverter" /><br />  <!-- other resources --><br /></Application.Resources><br /><br /><!-- in Page.xaml --><br /><phone:LongListSelector ItemsSource="{Binding Items}"><br />  <phone:LongListSelector.ItemTemplate><br />    <DataTemplate><br />      <StackPanel><br />        <TextBlock Text="{Binding Kind}" Style="{StaticResource PhoneTextLargeStyle}" /><br />        <TextBlock Text="{Binding Converter={StaticResource ItemToDescriptionConverter}}" /><br />      </StackPanel><br />    </DataTemplate><br />  </phone:LongListSelector.ItemTemplate><br /></phone:LongListSelector><br />
public class ObjectToResourceStringViewModel<br />{<br />  public IEnumerable<Item> Items { get; private set; }<br /><br />  public ObjectToResourceStringViewModel()<br />  {<br />    Items = new List<Item><br />    {<br />      new Item { Kind = "kind1"},<br />      new Item { Kind = "kind2"},<br />      new Item { Kind = "kind3"}<br />    };<br />  }<br />}<br />

The model of the above XAML page contains a single property – a collection of Items, which we display with the LongListSelector. Thanks to the fact that any converter is aware of the current culture, we will have a proper description string displayed for each of our items. As for the look of the page, it should be something like this: <o:p>


Finally, I would like to do something similar but a bit more appealing. Suppose you have a list of items, which should be displayed in the UI as nice images. The idea here is the same as with the localizable strings: in many cases the choice of image depends only on the values of some properties of an item, so there is no need to make room for the image itself in the model. To demonstrate this we use the same Item class with a single Kind property, to which we bind the Image’s source. As you might guess, we will need to create another converter to get an image for the Kind string. Here it is:

public class SocialKindToIconConverter : IValueConverter<br />{<br />  private const string _ImagePathFormat = "Assets/SocialIcons/social_{0}.png";<br />  private ImageSourceConverter _sourceConverter;<br /><br />  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)<br />  {<br />    var kind = (string)value;<br />    var path = String.Format(_ImagePathFormat, kind);<br />    return _sourceConverter.ConvertFromString(path);<br />  }<br /><br />  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)<br />  {<br />    throw new NotImplementedException();<br />  }<br /><br />  public SocialKindToIconConverter()<br />  {<br />    _sourceConverter = new ImageSourceConverter();<br />  }<br />}<br />

The images are stored in the Assets folder of the application package. Converter creates a path to the image from the argument and uses the ImageSourceConverter, which we mentioned above, to transform the path into actual ImageSource object expected by the control. The markup of the page doesn’t differ much from the previous examples and we still have no special logic in the viewmodel behind it:<o:p>

public class StringToImageViewModel<br />{<br />  public IEnumerable<Item> SocialItems { get; private set; }<br /><br />  public StringToImageViewModel()<br />  {<br />    SocialItems = new string[]<br />    {<br />      "facebook",<br />      "googleplus",<br />      "linkedin",<br />      "twitter",<br />      "microsoft",<br />      "foursquare"<br />    }.Select(s => new Item { Kind = s }).ToList();<br />  }<br />}<br />

<!-- in App.xaml --><br /><Application.Resources><br />  <local:SocialKindToIconConverter x:Key="SocialKindToIconConverter" /><br />  <!-- other resources --><br /></Application.Resources><br /><br /><!-- in page --><br /><phone:LongListSelector ItemsSource="{Binding SocialItems}" <br />            LayoutMode="Grid"<br />            GridCellSize="120,120" ><br />  <phone:LongListSelector.ItemTemplate><br />    <DataTemplate><br />      <Grid Width="100" Height="100" ><br />        <Rectangle Fill="{StaticResource PhoneAccentBrush}" /><br />        <Image Source="{Binding Kind, Converter={StaticResource SocialKindToIconConverter}}" <br />             Width="100" Height="100" /><br />      </Grid><br />    </DataTemplate><br />  </phone:LongListSelector.ItemTemplate><br /></phone:LongListSelector><br />

From my point of view, the result of introducing this simple converter is just amazing. First, we have these awesome social networks tiles on the page – one could go ahead and make them clickable, tiltable and otherwise interactive. On the other side, we didn’t have to make our model aware of them in any way: the Item class simply does not care whether its instances have something to do with Images or any other UI elements. Overall, it feels like a pretty good separation of concerns. <o:p>


I hope the examples above give you some idea on how one can benefit from the data conversion mechanism built into the Binding. Here I didn’t cover the reverse conversion, where one transforms the external representation of some property into the internal one. Such a thing is definitely possible with the ConvertBack method of the IValueConverter interface . The implementation of the backward conversion in some cases might be less trivial and clean than of the Convert method, but the idea is the same – experiment with it on your own.<o:p>

I can’t easily come up with any significant drawbacks of the data conversion mechanism apart from the fact that the converter classes live in a kind of isolation from other code. This is actually a common problem for all pieces of code in the presentation layer, which are linked together mainly by the XAML markup and auto-generated code behind it. This implies that you can’t always easily tell which components make up the UI of your application and there is little tooling to observe the relations between them. On the other side, this same isolation serves well to decouple different layers of the application. As I can’t stop repeating, converters play decently to make your models independent of the presentation and thus more maintainable, portable and testable. This fact combined with the simplicity and flexibility of the conversion mechanism makes it a very good thing to use in Windows Phone or any other XAML-based applications.<o:p>

As usual, the code for this post is available on GitHub – you are welcome to play with it. I will also be glad to hear any comments: tell me how your apps benefit from converters, where they don't help much and which important points about them I miss.

If you are not only a developer but a Windows Phone user as well, you might want to check out my recent app - Arithmo - it does utilize a number of custom data converters. :) I will be grateful if you just try it - even more so if you come back with any kind of feedback!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Acumatica
Russian Federation Russian Federation
I am a full-time .NET programmer and a lover of C#, C++, Clojure and Python at the same time. I do some Windows Phone development on my own and occasionally try myself at web-development. To enhance all these software-related activities I maintain a blog writing there on various topics, most of which actually come back to programming.

Comments and Discussions

 
-- There are no messages in this forum --