Xamarin.Forms: Android app forgets the style when using DynamicResource

If you break the look and feel of the app when you switch apps on mobile, and you use styles as DynamicResources, which you add as MergedDictionaries in App.Xaml,
you should pay attention to this:

When you don’t exit the Android app, but bring it back to the foreground after a very long time, the constructor logic in App.xaml.cs runs again. Don’t forget to add MergedDictionary from code, which contains the styles. If you forget this, all controls will appear in the app with their default look.

I wrote about how to handle restarting the application here: https://www.banditoth.hu/2021/03/22/xamarin-forms-reopening-application-best-pratices/

This content has 2 years. Some of the information in this post may be out of date or no longer work. Please, read this page keeping its age in your mind.

Xamarin.Forms : Using styles on custom UserControls

To use styles for your custom usercontrol, you have to define the styles TargetType property with an x:Type in your resource dictionary.

<ResourceDictionary
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:buttons="clr-namespace:AnAwesomeApp.Controls.Buttons"
    x:Class="AnAwesomeApp.Resources.Styles">

Declare the clr-namespace where your custom usercontrol lives.

<Style
        x:Key="BlueButtonStyle"
        TargetType="{x:Type buttons:ColoredButton}">
        <Setter
            Property="TextColor"
            Value="White" />
        <Setter
            Property="Color"
            Value="{AppThemeBinding Dark=#2325A6, Light=#61BAFF}" />
        <Setter
            Property="FontFamily"
            Value="Nunito" />
    </Style>

Set the target type with x:Type.

And boom, done!

This content has 3 years. Some of the information in this post may be out of date or no longer work. Please, read this page keeping its age in your mind.