现在,iOS 13和 Android Q允许用户在操作系统级别启用暗模式,我如何在 Xamarin.Forms 中检查它?
我已经在我的 Xamarin.Forms 项目中创建了它,但我不确定如何从 Xamarin.iOS 和 Xamarin.Android 检索值。
IEnvironment.cs
using System.Threading.Tasks;
namespace MyNamespace
{
public interface IEnvironment
{
Theme GetOperatingSystemTheme();
Task<Theme> GetOperatingSystemThemeAsync();
}
public enum Theme { Light, Dark }
}
应用程序
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
}
}
}
最佳答案
截至 2020 年 4 月的更新:
不再需要使用特定于平台的服务来检查 Xamarin.Forms 中的亮/暗模式。
我们现在可以通过以下方式直接获取当前主题:
OSAppTheme currentTheme = Application.Current.RequestedTheme;
哪里RequestedTheme
属性返回 OSAppTheme
枚举成员:Unspecified
, Dark
, 或 Light
.更多信息:见documentation和 updated Xamarin.Forms Application.cs code .
关于xamarin.forms - 如何在 Xamarin.Forms 中检查暗模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57879523/