如何在 Xamarin Forms 的 运行 时间内启用 OS AppTheme Dark/Light

How to enable OS AppTheme Dark/Light in Run time in Xamarin Forms

我正在关注 Respond to system theme change 以响应 xamarin 表单应用程序中的 OS 主题。该应用程序支持 AppThemeBinding 的深色和浅色主题。我没有使用任何自定义主题。我只关注 OS 个主题。所以我有一个 Switch,用户希望启用暗模式(与 OS 相同)。 link 建议使用以下代码启用指定模式(例如暗模式)。

Application.Current.UserAppTheme = OSAppTheme.Dark;

上面的代码没有任何作用,但是如果我把上面的代码写在App.cs之后InitializeComponent()应用程序就变成了Dark Mode.

然后我意识到在 Android 中重新启动 MainActivity,这是我在 Dependency 的帮助下完成的。

[assembly: Dependency(typeof(AndroidThemeChanged))]
    public class AndroidThemeChanged : ITheme
        {
            public void OnThemeChanged()
            {
                var activity = CrossCurrentActivity.Current.Activity;
                var intent = GetLauncherActivity();
                activity.Finish();
                activity.StartActivity(intent);
            }
            public static Intent GetLauncherActivity()
            {
                var packageName = AndroidApp.Context.PackageName;
                return AndroidApp.Context.PackageManager.GetLaunchIntentForPackage(packageName);
            }
        }

并调用它

if (Device.RuntimePlatform == Device.Android)
   DependencyService.Get<ITheme>().OnThemeChanged();

有没有什么方法可以在不重新启动 MainActivity 的情况下更新应用程序主题而不考虑 OS theme (Dark/Light)?

我想您不必重新启动 MainActivity。根据 documentation here,我们可以使用 Application.Current.RequestedThemeChanged 事件对主题更改做出反应。

Please make sure to follow the AppThemeBinding markup extension as per the documentation here.

试试下面的代码。

Application.Current.RequestedThemeChanged += Current_RequestedThemeChanged;

private void Current_RequestedThemeChanged(object sender, AppThemeChangedEventArgs e)
{
    if (e.RequestedTheme == OSAppTheme.Dark)
        Application.Current.UserAppTheme = OSAppTheme.Dark;
    else
        Application.Current.UserAppTheme = OSAppTheme.Light;
}

希望对您有所帮助。

我的错,我想我错了。我问题中的代码按预期工作。我不需要那个 Android 服务来重新启动 activity。 无论 OS 主题如何,从任何地方调用下面都会将主题更改为深色。

Application.Current.UserAppTheme = OSAppTheme.Dark;