Computer Magic Logo
Basic style

Tuesday, April 26, 2016

Published by Aristotelis Pitaridis

Sometimes we want to change the style of multiple controls. The following example demonstrates how to define a custom style for some of the labels of our form.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App1.Page1">
  <ContentPage.Resources>
    <ResourceDictionary>
      <Style x:Key="labelStyle" TargetType="Label">
        <Setter Property="HorizontalOptions" Value="Center" />                 
        <Setter Property="VerticalOptions" Value="CenterAndExpand" />                 
        <Setter Property="TextColor" Value="Red" />                 
        <Setter Property="FontSize" Value="Large" />
      </Style>
    </ResourceDictionary>
  </ContentPage.Resources>
  <StackLayout>
    <Label x:Name="MyLabel" Text="Hello World!" Style="{StaticResource labelStyle}" />
  </StackLayout>
</ContentPage>

We created a resource dictionary which has the key name labelStyle which has to be assigned to the label controls that we want to use our new style.