Wpf - 使用形状作为资源

时间:2013-11-13 09:33:49

标签: wpf resources shapes

我的资源字典中有一个Rectangle,我想放在很多Grid对象中

<Rectangle  HorizontalAlignment="Left" Width="10" x:Key="ShadowRect">
    <Rectangle.Fill>
        <LinearGradientBrush EndPoint="1.7,0.603" StartPoint="0.3,0.603">
            <GradientStop Color="White" Offset="1"/>
        <GradientStop Color="Black" Offset="0.009"/>                    
         </LinearGradientBrush>
    </Rectangle.Fill>                               
 </Rectangle>

现在我当然可以直接放置它:

 <Grid>
     <Rectangle  HorizontalAlignment="Left" Width="10" >
        <Rectangle.Fill>
          <LinearGradientBrush EndPoint="1.7,0.603" StartPoint="0.3,0.603">
              <GradientStop Color="White" Offset="1"/>
          <GradientStop Color="Black" Offset="0.009"/>                  
           </LinearGradientBrush>
         </Rectangle.Fill>                              
     </Rectangle>
 </Grid>

但我想将它用作资源,所以我不必为每个网格编写这个XAML,

如何使用它的资源键放置矩形?

1 个答案:

答案 0 :(得分:3)

您可以在ResourceDictionary中使用Rectangle Style而不是Rectangle:

<Style x:Key="ShadowRectStyle" TargetType="Rectangle">
    <Setter Property="HorizontalAlignment" Value="Left"/>
    <Setter Property="Width" Value="10"/>
    <Setter Property="Fill">
        <Setter.Value>
            <LinearGradientBrush EndPoint="1.7,0.603" StartPoint="0.3,0.603">
                <GradientStop Color="White" Offset="1"/>
                <GradientStop Color="Black" Offset="0.009"/>
            </LinearGradientBrush>
        </Setter.Value>
    </Setter>
</Style>

然后像这样使用它:

<Grid>
    <Rectangle Style="{StaticResource ShadowRectStyle}"/>
</Grid>