xamlxamarinstylesgroupstyle

How to define ResourceDictionary by adding Style in Xamarin xaml {GroupStyle}


I'm trying to make something like set atribute to all labels inside a grid

I Know how to make it, just doing this:

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

But Its Ugly and redundant

I want to do smetthing like

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

And On App Static Resources include the ResourceDictionary for the grid, something like:

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

I've being trying with a lot of ways but it's aways throw some kind of exception!

Can someone help-me Here?


Solution

  • I guess the most clean way to do this is by using Explicit Styles with Global Resources. Declare the style for that Labels in Application Resources and then in you label just add the Style Property:

    Application:

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

    And in your page:

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