如何通过在Xamarin xaml {GroupStyle}中添加Style来定义ResourceDictionary

时间:2016-07-05 14:19:20

标签: xaml xamarin styles groupstyle

我正在尝试为网格内的所有标签设置类似属性

我知道如何制作它,只是这样做:

<Grid RowSpacing="2" Padding="2,0,2,0">
    <Grid.Resources>
       <ResourceDictionary>
            <Style BasedOn="{StaticResource Font-Awesome}" TargetType="Label"/>
       </ResourceDictionary>
    </Grid.Resources>
        <Label Text="31 &#xf083;" Grid.Column="0" TextColor="#2764B5" XAlign="Start"/>

        <Label Text="91 &#xf083;" Grid.Column="1" TextColor="#A0A1A2" XAlign="Center"/>

        <Label Text="12 &#xf083;" Grid.Column="2" TextColor="#A0A1A2" XAlign="End"/>
</Grid>

但它的丑陋和多余

我想做像

这样的事情
<Grid RowSpacing="2" Padding="2,0,2,0" Style="{StaticResource grd-actions}">
    <Label Text="31 &#xf083;" Grid.Column="0" TextColor="#2764B5" XAlign="Start"/>

    <Label Text="91 &#xf083;" Grid.Column="1" TextColor="#A0A1A2" XAlign="Center"/>

    <Label Text="Compartilhar &#xf083;" Grid.Column="2" TextColor="#A0A1A2" XAlign="End"/>
</Grid>

On App Static Resources包含网格的ResourceDictionary,如:

<Style x:Key="gd-actions" TargetType="Grid">
    <Setter Property="Resources">
      <Setter.Value>
        <ResourceDictionary>
          <Style BasedOn="{StaticResource Font-Awesome}" TargetType="Label"/>
        </ResourceDictionary>
      </Setter.Value>
    </Setter>
</Style>

我正在尝试很多方法,但它会带来某种异常!

有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

我想最干净的方法是将Explicit StylesGlobal Resources一起使用。在Labels中声明Application Resources的样式,然后在标签中添加Style Property

应用:

<Application xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="xforms_test.App">
    <Application.Resources>
        <ResourceDictionary>
            <Style x:Key="labelAquaStyle" TargetType="Label">
                <Setter Property="HorizontalOptions" Value="Center" />
                <Setter Property="TextColor" Value="Aqua" />
            </Style>
        </ResourceDictionary>
    </Application.Resources>
</Application>

在您的页面中:

<Grid RowSpacing="2" Padding="2,0,2,0">
    <Label Grid.Column="0" Text="These labels" Style="{StaticResource labelAquaStyle}" />
    <Label Grid.Column="1" Text="are demonstrating" Style="{StaticResource labelAquaStyle}" />
    <Label Grid.Column="2" Text="explicit styles" Style="{StaticResource labelAquaStyle}" />
</Grid>