(616) 371-1037

[email protected]

Implementing Dark & Light Modes in Xamarin.Forms Apps

February 22, 2021 - Rodrigo Juarez

1 Comment

With modern mobile devices supporting both dark & light modes, users expect applications to respect those settings.

Since Xamarin.Forms version 4.6.0.967, we can easily add support to our apps using the AppThemeBinding markup extension. In the blog, I will show you the most interesting parts needed to implement this functionality with a sample application.

You can access a fully functional example in this public GitHub repository.

Dark & Light sample app demo

The first step is to define styles using AppThemeBinding, and in there we can define the colors to use for dark & light modes.

Define Styles

And then we can use the styles in our XAML files.

Xaml files using styles

The only remaining task is to set the value of the property App.Current.UserAppTheme. The type for that property is the enum OSAppTheme. OSAppTheme.Unspecified uses the system default configuration and OSAppTheme.Light or OSAppTheme.Dark will force the use of the selected theme.

You can set the value of UserAppTheme at run-time and the setting will work immediately.

In the code sample, we are using Xamarin.Essentials.Preferences to save the latest selected value and then reload the configuration when the application starts.

public App()
{
   InitializeComponent();

   var theme = Preferences.Get("OSAppTheme", Enum.GetName(typeof(OSAppTheme), OSAppTheme.Unspecified));
   App.Current.UserAppTheme = (OSAppTheme)Enum.Parse(typeof(OSAppTheme), theme);

   MainPage = new MainPage();
}

And that’s all! I hope you learn how easy is to use Dark & Light modes in your Xamarin.Forms app, if you want more information you can access the official docs here.

Rodrigo Juarez

I'm a full-stack and Xamarin Certified Mobile Professional developer. My mission is to solve complex problems for my clients focusing on the results, applying the most adequate technology available and best practices to ensure a cost-effective and high-quality solution. I have 20+ years of experience in a wide variety of projects in the development of applications for web, desktop, and mobile using Microsoft technologies in areas such as management, services, insurance, pharmacy, and banks.

One thought on “Implementing Dark & Light Modes in Xamarin.Forms Apps

Leave a comment

Your email address will not be published. Required fields are marked *