Search code examples
c#silverlightsilverlight-4.0colorsfill

In Silverlight 4: how to get the color out of the Fill property


in my XAML i have:

<Canvas Grid.Row="1" Background="#FFF2F2F2" Width="78" HorizontalAlignment="Left">
            <Rectangle Height="67" x:Name="rectFront" Width="70" Fill="#FF000000" Stroke="#FFB9B9B9" StrokeThickness="3" StrokeLineJoin="Miter" StrokeStartLineCap="Flat" Stretch="Uniform" Canvas.Left="4"/>
</Canvas>

in the CS code:

someColor = rectFront.Fill; // <-- error here, can't convert Brush to Color

which totally makes sense. But how can i convert the color attribute from the Brush out of the Fill?

Thanks

Simple Code


Solution

  • here is the problem.... there are several different types of brushes. so, you are going to have to access the color property differently depending on the type of brush you get.

    SolidColorBrush
    LinearGradientBrush
    RadialGradientBrush

    if you want the brush color, and it is a SolidColorBrush then you can cast it and get the color that way:

    if ( rectFront.Fill is SolidColorBrush ) 
    {
          SolidColorBrush brush = rectFront.Fill as SolidColorBrush;
          someColor = brush.Color
    }
    

    otherwise, you are going to have to access the GradientStops collection:

    // Generally a GradientStopCollection contains a minimum of two gradient stops.
    if ( rectFront.Fill is GradientBrush )
    {
        GradientBrush brush = rectFront.Fill as GradientBrush ;
        someColor = brush.GradientStops[ 0 ].Color
    }