Automatic Dark Theme with Xamarin.Forms
Automatic theme switching is coming to Xamarin.Forms. In Xamarin.Forms 4.6 they added a new Experimental Flag called AppTheme_Experimental
. This provides a a simple cross-platfrom solution for developers to use, giving access to the current device theme as well as an event that will fire when the device theme is changed.
As this is currently an experimental feature you will need to enable the flag. You can read more about Xamarin.Forms Experimental features here. Also, because this is an experimental feature, it may mean that changes are made without much notice and allows the developers to iterate on the feature before declaring it stable.
In your app.xaml.cs
add the following to enable AppTheme detection. If you forget to do this, you’ll get an exception when you try to use it. It’s descriptive and will remind you, so don’t panic!
Device.SetFlags(new string[] { "AppTheme_Experimental" });
Detecting the theme
Similar to the way that Xamarin.Essentials returns the device theme information, Xamarin.Forms also provides access via one line of code.
OSAppTheme appTheme = Application.Current.RequestedTheme
This will return an OSAppTheme
enum, which contains the same options as the Xamarin.Essentials implementation. Dark, Light and unspecified.
Responding to the theme change
Xamarin.Forms doesn’t just let you detec the theme (Similar to Xamarin.Essentials), it also exposes an event that allows you to detect when the phone’s theme has changed (Xamarin.Essentials doesn’t do this yet), this can be for many reasons, such as the user has initiated the change or because of an automatic setting on the phone, e.g. sunset.
In your app.xaml.cs
you can add the following:
Application.Current.RequestedThemeChanged += (s, a) => {
switch(a.RequestedTheme) {
case OSAppTheme.Dark:
Current.Resources = new DarkTheme();
break;
case OSAppTheme.Light:
Current.Resources = new LightTheme();
break;
case OSAppTheme.Unspecified:
Current.Resources = new LightTheme();
break;
}
};
Resources
Update 22/02/2021: If you would like to find more information on building app themes, check out my post on App Themes in the Xamarin Lets Build series.
As always, you can find the code for these examples here
Comments