Xamarin.Forms 1.3 introduced styles as static resources. That means that you can define a style once on the page or on the entire application and use it on different UI controls. Xamarin.Forms 1.3 also added the concept of triggers. This comes in handy when you want to highlight UI controls in the view when properties in the view model changes. You can change the style of a certain UI control based on a property in the view model by using triggers in Xamarin.Forms.

First you declare styles on the page as follows:

<ContentPage.Resources>
  <ResourceDictionary>
    <Style x:Key="LabelStyle" TargetType="Label">
      <Setter Property="TextColor" Value="Color.Black"/>
      <Setter Property="FontAttributes" Value="None" />
    </Style>
    <Style x:Key="LabelChangedStyle" TargetType="Label">
      <Setter Property="TextColor" Value="Color.White"/>
      <Setter Property="FontAttributes" Value="Bold" />
    </Style>
  </ResourceDictionary>
</ContentPage.Resources>

You then declare a boolean property in the view model, in this case its called HasPropertyValueChanged.
Then based on the value of HasPropertyValueChanged, you can set the style of the Label like this:

<Label Text="{Binding PropertyValue}" Style="{StaticResource LabelStyle}" >
  <Label.Triggers>
    <DataTrigger TargetType="Label"
                 Binding="{Binding HasPropertyValueChanged}"
                 Value="true">
      <Setter Property="Style" Value="{StaticResource LabelChangedStyle}" />
    </DataTrigger>
  </Label.Triggers>
</Label>

This means that when HasPropertyValueChanged is true, the style LabelChangedStyle is applied to the Label. If the value if false, the style LabelStyle is used.

This way you can keep your view model clean from any view-related properties like textcolor and font attributes.

Good luck in your Xamarin coding!

One Reply to “Changing style with trigger in Xamarin.Forms if view model property changes”

Comments are closed.