1

在我的 XAML 中,我有:

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

在 CS 代码中:

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

这完全有道理。但是我怎样才能将画笔中的颜色属性从填充中转换出来呢?

谢谢

简单代码

4

2 回答 2

4

将其投射到 SolidColorBrush;

var brush = rectFront.Fill as SolidColorBrush;
if(brush != null)
    someColor = brush.Color
于 2010-11-19T20:07:04.837 回答
2

这是问题....有几种不同类型的刷子。因此,您将不得不根据您获得的画笔类型以不同的方式访问颜色属性。

SolidColorBrush
LinearGradientBrush
RadialGradientBrush

如果您想要画笔颜色,并且它是 SolidColorBrush,那么您可以投射它并以这种方式获取颜色:

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

否则,您将不得不访问 GradientStops 集合:

// 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
}
于 2010-11-19T20:12:32.497 回答