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.
The first step is to define styles using AppThemeBinding, and in there we can define the colors to use for dark & light modes.
And then we can use the styles in our XAML files.
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.