1

我的资源字典中有一个 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>

但我想将其用作资源,因此我不必为每个 Grid 编写此 XAML,

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

4

1 回答 1

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>
于 2013-11-13T10:18:16.050 回答