19 February 2011

Converter to convert a single item to a list to enable Bing Maps binding

Some things are so simple that I wonder if I am missing something. I tried to bind a single GeoPosition to Bing Maps’ MapItemsControl ItemsSource on Windows Phone 7 and it did not work. Apparently Bing Maps want a list. So I wrote the following converter:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Data;

namespace LocalJoost.Convertors
{
  public class ToListConverter : IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, 
                          CultureInfo culture)
    {
      var l = new List<object> ();
      if (value != null) l.Add(value);
      return l;
    }

    public object ConvertBack(object value, Type targetType, object parameter, 
                              CultureInfo culture)
    {
      return null;
    }
  }
}
A masterpiece of complicated coding, right :-/ ? Anyway, in stead of
<Microsoft_Phone_Controls_Maps:MapItemsControl 
  ItemsSource="{Binding GpsLocation}">
I used
<Microsoft_Phone_Controls_Maps:MapItemsControl 
  ItemsSource="{Binding GpsLocation, Converter={StaticResource ToListConverter}}">

and Lo and Behold – now I did get my single icon on the map.

I have no idea if this is a quirk of the Bing Maps control or that ItemsSource attributes in general only accept lists – but either way, this works.

No comments: