Wednesday, 31 August 2011

Extend MapPolygon to allow binding to Fill Parameter

The Silverlight Bing Maps Control library has a MapPolygon control to allow you to overlay geo-located polygons over your Bing Map.

The MapPolygon control has a property Fill that is used to set the fill Brush for the polygon, but there is no DependencyProperty for the Fill property and it cannot be set using a Binding statement in XAML.
One Solution for this is to extend the MapPolygon control to add a DependencyProperty for Fill.
Here is how you may implement this:
Public Class MapPolygonExtended

Inherits Microsoft.Maps.MapControl.MapPolygon

Public Shared ReadOnly FillProperty As DependencyProperty = DependencyProperty.RegisterAttached("Fill", GetType(Brush), GetType(MapPolygonExtended),
New PropertyMetadata(New PropertyChangedCallback(AddressOf FillChangedCallback)))

Public Overloads Property Fill() As Brush
Get
Return MyBase.Fill
End Get
Set(ByVal value As Brush)
MyBase.Fill = value
End Set
End Property

Private Shared Sub FillChangedCallback(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
Dim dlb As MapPolygonExtended = CType(d, MapPolygonExtended)
dlb.Fill = CType(e.NewValue, Brush)
End Sub

End Class

This then allows you to bind to the Fill property of your new extended control:

<local:MapPolygonExtended Fill=”{Binding Path=FillColour}” >

If the bound property is already of type Brush then it should just work as long as you have set the locations for the points of the polygon.

If it is another type such as a Color or String then you will need to use a binding converter.

I hope this can help people setup bound MapPolygon.

Happy Coding and Mapping

No comments: