开发者

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开发者_StackOverflow中文版 makes sense. But how can i convert the color attribute from the Brush out of the Fill?

Thanks

Simple Code


Cast it to a SolidColorBrush;

var brush = rectFront.Fill as SolidColorBrush;
if(brush != null)
    someColor = brush.Color


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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜