Finn Alberts
Finn Alberts

Reputation: 25

Manually apply dark theme in Xamarin.Forms

I'm currently creating an Android-app using Xamarin.Forms. I'm trying to implement a settings menu where the user can choose which theme he/she wants to use (system default/light/dark). The system default works fine and dark theme and light theme work as expected.

See images: Light theme Dark theme

The problem I'm having however is that I seem to be unable to set the app to dark mode manually. What I mean by that is that I'm able to change the colors of e.g. the background and text, but not the color of the background for the DisplayAlert or placeholder text.

I tried using Application.Current.UserAppTheme = OSAppTheme.Dark; but this doesn't seem to do anything (I checked that it was actually set by printing Application.Current.UserAppTheme to the console). What am I missing here? How do I set dark theme manually so that dialog boxes look like the one shown in the image above.

Any help would be appreciated.

Finn

Upvotes: 1

Views: 978

Answers (1)

ColeX
ColeX

Reputation: 14463

Application.Current.UserAppTheme only applys for the theme defined with AppThemeBinding, but the dialog is build-in we can't customize the color so it would not work in this way .

To manually enable/disable the dark theme ,we have to implement on each platform and invoke it in forms with Dependency service .

Android Solution

  1. Change the default theme in styles.xml .
 <style name="MainTheme" parent="Theme.AppCompat.DayNight.DarkActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>  
  </style>
  1. Define a new interface in Forms
 public interface IChangeTheme
    {
        void EnableDarkTheme(bool _);
    }
  1. Implement on Android platform
[assembly: Dependency(typeof(Changetheme))]
namespace FormsApp.Droid
{
    class Changetheme : IChangeTheme
    {
        public void EnableDarkTheme(bool _)
        {
            AppCompatDelegate.DefaultNightMode = _ ? AppCompatDelegate.ModeNightYes : AppCompatDelegate.ModeNightNo;
        }
    }
}
  1. Invoke in Forms
DependencyService.Get<IChangeTheme>().EnableDarkTheme(true);

Refer to https://stackoverflow.com/a/61891471/8187800

iOS Solution

Same way with android solution , I haven't test it but it should work , refer to https://stackoverflow.com/a/60171521/8187800.

Upvotes: 4

Related Questions