Data Binding with the Virtual Earth Control

I was very excited to hear that the Virtual Earth (VE) team was creating a Silverlight control and that they announced at Mix a CTP (Community Technology Preview).  I promptly downloaded it and started playing with it.  From the Circus Mashimus contest I entered, I had learned about the Best Buy Remix APIs that let me search for products, stores, and product availability at stores using a simple REST API.  The Stores API actually returns Longitude/Latitude coordinates.

When I started looking at the VE control, it was apparent that the control was missing some features related to data binding:  I wanted to bind the coordinates returned from the Stores Service to shapes in the Map Layer, use a data templates to define what each store shape would look like, and synchronize the selection of stores in a listbox to the center of the map.

Take a look here to see the app.

It turns out that because of the power of XAML and Silverlight’s .NET framework, I can add my own attached properties to any dependency object using Custom Attached Properties.  This let me do binding and use templates just like a ListBox or DataGrid.  So to create an example like the one in the picture where I want a BestBuy logo placed whereever there is a Best Buy Store, I want to use a Data Template like this:

 <DataTemplate x:Key="BestBuyShape">
    <Image Stretch="None" 
        ToolTipService.ToolTip="{Binding Name}"
        Source="{Binding Logo, Source={StaticResource StoresDS}}" 
        m:MapLayer.MapPosition="{Binding Converter={StaticResource StoreToLocationConverter}}"
        m:MapLayer.MapPositionMethod="BottomLeft"/>
</DataTemplate>

and then that template is used with a data source here:

 <m:Map Grid.Row="1" Margin="4" Grid.Column="1" Mode="AerialWithLabels" x:Name="Map" 
    ve:Properties.CenterPoint="{Binding SelectedStore, Source={StaticResource ViewModel}, Converter={StaticResource StoreToLocationConverter}}">
    <m:Map.Children>
        <m:MapLayer x:Name="BestBuyLocations" 
             ve:Properties.ItemsSource="{Binding Items, Source={StaticResource StoresDS}}"
             ve:Properties.ItemTemplate="{StaticResource BestBuyShape}"/>
    </m:Map.Children>
</m:Map>

I’ve shared the source code for these useful properties on the MSDN Code Gallery so you can use them too.  Tell me what you think and what you use them for.  I will be releasing a Best Buy kit for Silverlight soon so you can the very cool service as well.  image

5/24/2009 - MSS - Updated URL to Stores Service Documentation.