在 Xamarin 中执行主题

Enforce theme in Xamarin

我想在我的 android 应用程序中强制使用 lightmode 主题。

我已将这行代码添加到 app.cs

public partial class App : Application
{
    public App()
    {
        InitializeComponent();
        App.Current.UserAppTheme = OSAppTheme.Light;
        MainPage = new MainPage();
    }

我读了这个 https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/theming/system-theme-changes 但不明白我错过了什么。

分配 App.Current.UserAppTheme 是不够的,您必须使用 xaml 扩展名 AppThemeBinding 通过样式为不同的控件定义浅色 or/and 深色主题,如示例所示在文档中 link.

我通过将这行代码放在 Android 项目

的 MainActivity.cs 中解决了这个问题
AppCompatDelegate.DefaultNightMode = AppCompatDelegate.ModeNightNo;

将这行代码直接放在 OnCreate 方法的开头即可解决问题。

如果您打算让您的 XF 应用程序跨平台并且您不会在主题之间切换,您可以通过在自定义页面渲染器中设置 OverrideUserInterfaceStyle 强制在 iOS 上使用浅色主题:

using TheNameSpace;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(ContentPage), typeof(CustomPageRenderer))]
namespace TheNameSpace
{
    public class CustomPageRenderer : PageRenderer
    {
        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

            OverrideUserInterfaceStyle = UIUserInterfaceStyle.Light;
        }
    }
}