Estilos explícitos em Xamarin.Forms

Baixar exemplo Baixar o exemplo

Um estilo explícito é aquele que é aplicado seletivamente aos controles definindo suas propriedades style.

Criar um estilo explícito em XAML

Para declarar um Style no nível da página, um ResourceDictionary deve ser adicionado à página e, em seguida, uma ou mais Style declarações podem ser incluídas no ResourceDictionary. Um Style é explicitado dando a sua declaração um x:Key atributo, o que lhe dá uma chave descritiva no ResourceDictionary. Os estilos explícitos devem ser aplicados a elementos visuais específicos definindo suas Style propriedades.

O exemplo de código a seguir mostra estilos explícitos declarados em XAML em uma página ResourceDictionary e aplicados às instâncias da Label página:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Styles.ExplicitStylesPage" Title="Explicit" IconImageSource="xaml.png">
    <ContentPage.Resources>
        <ResourceDictionary>
            <Style x:Key="labelRedStyle" TargetType="Label">
                <Setter Property="HorizontalOptions"
                        Value="Center" />
                <Setter Property="VerticalOptions"
                        Value="CenterAndExpand" />
                <Setter Property="FontSize" Value="Large" />
                <Setter Property="TextColor" Value="Red" />
            </Style>
            <Style x:Key="labelGreenStyle" TargetType="Label">
                ...
                <Setter Property="TextColor" Value="Green" />
            </Style>
            <Style x:Key="labelBlueStyle" TargetType="Label">
                ...
                <Setter Property="TextColor" Value="Blue" />
            </Style>
        </ResourceDictionary>
    </ContentPage.Resources>
    <ContentPage.Content>
        <StackLayout Padding="0,20,0,0">
            <Label Text="These labels"
                   Style="{StaticResource labelRedStyle}" />
            <Label Text="are demonstrating"
                   Style="{StaticResource labelGreenStyle}" />
            <Label Text="explicit styles,"
                   Style="{StaticResource labelBlueStyle}" />
            <Label Text="and an explicit style override"
                   Style="{StaticResource labelBlueStyle}"
                   TextColor="Teal" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

O ResourceDictionary define três estilos explícitos que são aplicados às instâncias da Label página. Cada Style um é usado para exibir texto em uma cor diferente, ao mesmo tempo em que define o tamanho da fonte e as opções de layout horizontal e vertical. Cada Style um é aplicado a um diferente Label definindo suas Style propriedades usando a StaticResource extensão de marcação. Isso resulta na aparência mostrada nas capturas de tela seguir:

Exemplo de estilos explícitos

Além disso, o final Label tem um Style aplicado a ele, mas também substitui a TextColor propriedade por um valor diferente Color .

Criar um estilo explícito no nível de controle

Além de criar estilos explícitos no nível da página, eles também podem ser criados no nível de controle, conforme mostrado no exemplo de código a seguir:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Styles.ExplicitStylesPage" Title="Explicit" IconImageSource="xaml.png">
    <ContentPage.Content>
        <StackLayout Padding="0,20,0,0">
            <StackLayout.Resources>
                <ResourceDictionary>
                    <Style x:Key="labelRedStyle" TargetType="Label">
                      ...
                    </Style>
                    ...
                </ResourceDictionary>
            </StackLayout.Resources>
            <Label Text="These labels" Style="{StaticResource labelRedStyle}" />
            ...
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Neste exemplo, as instâncias explícitasStyle são atribuídas à Resources coleção do StackLayout controle . Em seguida, os estilos podem ser aplicados ao controle e seus filhos.

Para obter informações sobre como criar estilos no de ResourceDictionaryum aplicativo, consulte Estilos globais.

Criar um estilo explícito em C#

Style As instâncias podem ser adicionadas à coleção de Resources uma página em C# criando um novo ResourceDictionarye, em seguida, adicionando as Style instâncias ao ResourceDictionary, conforme mostrado no exemplo de código a seguir:

public class ExplicitStylesPageCS : ContentPage
{
    public ExplicitStylesPageCS ()
    {
        var labelRedStyle = new Style (typeof(Label)) {
            Setters = {
                ...
                new Setter { Property = Label.TextColorProperty, Value = Color.Red    }
            }
        };
        var labelGreenStyle = new Style (typeof(Label)) {
            Setters = {
                ...
                new Setter { Property = Label.TextColorProperty, Value = Color.Green }
            }
        };
        var labelBlueStyle = new Style (typeof(Label)) {
            Setters = {
                ...
                new Setter { Property = Label.TextColorProperty, Value = Color.Blue }
            }
        };

        Resources = new ResourceDictionary ();
        Resources.Add ("labelRedStyle", labelRedStyle);
        Resources.Add ("labelGreenStyle", labelGreenStyle);
        Resources.Add ("labelBlueStyle", labelBlueStyle);
        ...

        Content = new StackLayout {
            Children = {
                new Label { Text = "These labels",
                            Style = (Style)Resources ["labelRedStyle"] },
                new Label { Text = "are demonstrating",
                            Style = (Style)Resources ["labelGreenStyle"] },
                new Label { Text = "explicit styles,",
                            Style = (Style)Resources ["labelBlueStyle"] },
                new Label {    Text = "and an explicit style override",
                            Style = (Style)Resources ["labelBlueStyle"], TextColor = Color.Teal }
            }
        };
    }
}

O construtor define três estilos explícitos que são aplicados às instâncias da Label página. Cada explícitoStyle é adicionado ao ResourceDictionary usando o Add método , especificando uma cadeia key de caracteres para se referir à Style instância. Cada Style um é aplicado a um diferente Label definindo suas Style propriedades.

No entanto, não há nenhuma vantagem em usar um ResourceDictionary aqui. Em vez disso, Style as instâncias podem ser atribuídas diretamente às Style propriedades dos elementos visuais necessários e podem ResourceDictionary ser removidas, conforme mostrado no exemplo de código a seguir:

public class ExplicitStylesPageCS : ContentPage
{
    public ExplicitStylesPageCS ()
    {
        var labelRedStyle = new Style (typeof(Label)) {
            ...
        };
        var labelGreenStyle = new Style (typeof(Label)) {
            ...
        };
        var labelBlueStyle = new Style (typeof(Label)) {
            ...
        };
        ...
        Content = new StackLayout {
            Children = {
                new Label { Text = "These labels", Style = labelRedStyle },
                new Label { Text = "are demonstrating", Style = labelGreenStyle },
                new Label { Text = "explicit styles,", Style = labelBlueStyle },
                new Label { Text = "and an explicit style override", Style = labelBlueStyle,
                            TextColor = Color.Teal }
            }
        };
    }
}

O construtor define três estilos explícitos que são aplicados às instâncias da Label página. Cada Style um é usado para exibir texto em uma cor diferente, ao mesmo tempo em que define o tamanho da fonte e as opções de layout horizontal e vertical. Cada Style um é aplicado a um diferente Label definindo suas Style propriedades. Além disso, o final Label tem um Style aplicado a ele, mas também substitui a TextColor propriedade por um valor diferente Color .