Search code examples
silverlightwindows-phone-7bing-maps

Styling a MapPolygon


I was going to create a Style for MapPolygon, but I can't seem to add a Setter for anything other than the properties inherited from Control, which doesn't help very much since the MapPolygon doesn't actually use many of those properties.

I mainly want to be able to style the Fill, Stroke, and StrokeThickness properties. When I try to do this, however, I get the following error: "Object reference not set to an instance of an object". Am I correct in thinking this is because the properties that I am trying to style are not dependency properties (DependencyProperty)?

If my thinking here is indeed correct, would the easiest way to solve this problem be to create a custom MapPolygon control and create dependency properties for Fill, Stroke, and StrokeThickness?

Let me know if I need to clarify something.

Update:

public class StyledMapPolygon : MapPolygon {
    public static readonly DependencyProperty FillProperty =
       DependencyProperty.Register("Fill", typeof(Brush), typeof(StyledMapPolygon),
       new PropertyMetadata(new SolidColorBrush(), new PropertyChangedCallback(OnFillChanged)));

    private static void OnFillChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
        StyledMapPolygon instance = (StyledMapPolygon) d;
        instance.Fill = e.NewValue as Brush;
    }
}

.

<Style x:Key="CustomStyle" TargetType="exts:StyledMapPolygon">
        <Setter Property="Fill" Value="{StaticResource BuildingFillBrush}" />
</Style>

This is just a simplified version of a style that I would like to use. the StyledMapPolygon is a object I created inherited from MapPolygon. The only difference is that I created a DependencyProperty for "Fill" that just maps to the base property.

The error mentioned above still appears on "Fill" within the Setter, but it now works (displays correctly on the phone). I can live with the error there since it still runs, but I would very much like to have my app be error free.


Solution

  • Yes, a property must be a DependencyProperty in order to be set by a style.

    There's nothing wrong with adding your own dependency property that wraps a property on the base class, but I wouldn't recommend trying to use the same property name. Create a differently named property, with property changed handler which relays the value which is set to the underlying property.

    Of course if the "error" you mention is Intellisense there's really no reason to care, so long as code compiles and runs.