Saturday, September 6, 2014

Windows Phone 8: The Map control

Recently I've been hitting an issue with integrating the Map control from the Windows Phone Toolkit into the UI. The problem was related to centering map to the desired location. I was using MVVM pattern for the app, so I had a proper public property in the data context, which I was trying to set as a binding source for the Center property of the Map control.

As I was just interested in centering map based on the property value, and not vice-versa, I've had explicitly specified the Mode property for the binding to be "One Way". And that was the problem.
It turns out, that for the Center property to work properly, you have to have the binding mode set to "Two Way".

So the final property and the XAML should be similar to the following to work:

The following property is the one defined in the data context:
public GeoCoordinate MapCenterLocation
{
 
get
  {
   
return this.mapCenterLocation;
  }
 
set
  {
 
   if (value != this.mapCenterLocation)
    {
 
     this.NotifyPropertyChanging(MapCenterLocationPropertyName);
      this.mapCenterLocation = value;
      this.NotifyPropertyChanged(MapCenterLocationPropertyName);
    }
  }
}


and the appropriate XAML for the map control should be:
<maps:Map x:Name="map"
  HorizontalAlignment="Stretch"
  VerticalAlignment="Stretch"
   Center="{Binding Path=MapCenterLocation, Mode=TwoWay}" />

As mentioned above - the "Mode=TwoWay" is critical for the Center property binding to work. Otherwise, the map will never be centered like the binding is not there.
Interestingly, you don't even get an error/warning for that.