Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
799 views
in Technique[技术] by (71.8m points)

xamarin.android - How to Check For Dark Mode in Xamarin.Forms

Now that iOS 13 and Android Q allow the user to enable Dark Mode at the operating system level, how can I check for it in Xamarin.Forms?

I've created this in my Xamarin.Forms project, but I'm not sure how to retrieve the values from Xamarin.iOS and Xamarin.Android.

IEnvironment.cs

using System.Threading.Tasks;

namespace MyNamespace
{
    public interface IEnvironment
    {
        Theme GetOperatingSystemTheme();
        Task<Theme> GetOperatingSystemThemeAsync();
    }

    public enum Theme { Light, Dark }
}

App.cs

using Xamarin.Forms;

namespace MyNamespace
{
    public App : Application
    {
        // ...

        protected override async void OnStart()
        {
            base.OnStart();

            Theme theme = DependencyService.Get<IEnvironment>().GetOperatingSystemTheme();

            SetTheme(theme);
        }

        protected override async void OnResume()
        {
            base.OnResume();

            Theme theme = DependencyService.Get<IEnvironment>().GetOperatingSystemTheme();

            SetTheme(theme);
        }

        void SetTheme(Theme theme)
        {
            //Handle Light Theme & Dark Theme
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

UPDATE as of April 2020:

It is no longer necessary to use platform-specific services to check for light/dark mode in Xamarin.Forms.

We can now get the current theme directly via:

OSAppTheme currentTheme = Application.Current.RequestedTheme;

where the RequestedTheme property returns an OSAppTheme enumeration member: Unspecified, Dark, or Light.

For more info: see documentation and the updated Xamarin.Forms Application.cs code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...