Estilos explícitos em Xamarin.Forms
Um estilo explícito é aquele que é aplicado seletivamente aos controles definindo suas propriedades style.
Criar um estilo explícito no XAML
Para declarar um Style no nível da página, é ResourceDictionary necessário adicionar à 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 uma é aplicada a uma 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:
Além disso, a final Label tem uma Style aplicada a ela, mas também substitui a TextColor propriedade a 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 aos filhos.
Para obter informações sobre como criar estilos em um aplicativo ResourceDictionary, 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 uma nova 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 uso do ResourceDictionaryAdd método, especificando uma key cadeia de caracteres para fazer referência à 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, a final Label tem uma Style aplicada a ela, mas também substitui a TextColor propriedade a um valor diferente Color .
Baixar o exemplo