Handling Pushpins selection with the WP7 Map control

by CameronM 23. December 2011 07:14

As mentioned in the previous post, one of the benefits of using your own custom business objects as the data source for your Map control Pushpin layer is that you can access all the information about the item you select.

So how do we get back a single Camera object when a user presses on a pushpin? Well thankfully this is very easy. By using a List<Camera> as the ItemSource for the MapsItemControl control containing our Pushpins we are able to extract the data back when the user presses the Pushpin.

There are a number of methods you can use that are triggered when the user clicks or taps on the screen, but in this example we will use the new ‘Tap’ event, made available in the Mango release. The map xaml has been covered in the previous post, but now all we need to do is add the Tap event handler such as:

<my:Pushpin Location="{Binding Location}" Tap="Pushpin_Tap" >

</my:Pushpin>

The key to unlocking all the goodness obtained by binding the pushpins to your own objects is to realise that the DataContext of the Pushpin actually contains your business object.

private void Pushpin_Tap(object sender, System.Windows.Input.GestureEventArgs e)

{

var pushpin = sender as Pushpin;

 

Camera cam= (Camera)pushpin.DataContext;

MessageBox.Show(cam.Name);

}


In this example we can direct cast the Pushpin.DataContext to our business object, which in this example is called Camera. Once we have a Camera object, we can access any of the properties and methods associated with it.

Obviously you could do a lot more than simply displaying a message when the Pushpin is selected, for example you could navigate to another page displaying information relevant to the selected Pushpin.

 

Tags: ,

WP7