Well when you are developing on the Windows Phone and are trying to use MVVM, you’ll notice not everything is ‘real’ MVVMable 🙂
You’ll notice it mostly when you are using controls that don’t have much bindable items… so sometimes you’ll loose control of the View – ViewModel link.
An example I came across, where I was stuck with using the normal MVVM way, was when I added some pushpins on a Bing Maps control and wanted to adjust the view of the Bing Maps so that it would show all pushpins just added!
There is a real nice method on the Bing Maps called SetView()! It accepts a LocationRect as parameter and you can create such a LocationRect from a IEnumerable list of Geocoördinates. In other words if you have the PushPin collection, you can pass this along and the Bing Map will zoom and center to an appropriate size / place to show all pushpins in the given collection.
But the bad part, the SetView is a method and there is no bindable property on the map to use to control this. So you are a bit stuck when you only want to use the MVVM pattern.
So how to solve this, well it’s actually very easy 😉
When you are using the MVVMLight Toolkit from Laurent Bugnion, you can use the Messaging feature for this!
So what do you need to do.
First create a class inside the Model folder ( or in the root of the project ) called PushPinModel and add a List<Geocoordinate> GeoCoordinateList property inside of it.
Then assuming you have a MainPage View, add following in the constructor of this MainPage.xaml.cs
Messenger.Default.Register<PushPinModel>(this, action => this.SetView(action));
Also add following private method inside the MainPage.xaml.cs, this method will be called each time the listener receives a message!
private void SetView(PushPinModel pushpinModel)
if (pushpinModel.GeoCoordinateList.Count > 0)
Now the only thing left to do is fill up this Geocoordinate list in the ViewModel and send out a message to the listeners!
PushPinModel pm = new PushPinModel();
pm.GeoCoordinateList.Add(new GeoCoordinate(51.10524, 4.54229));
pm.GeoCoordinateList.Add(new GeoCoordinate(51.3411, 3.2398));