问题描述
我的Xamarin.Forms应用程序(Shell项目)在启用了深色主题的Android手机上会自动切换到深色主题。我不希望这种情况发生。我尝试了多种方法来禁用此功能,但没有一种有效。 知道怎么了吗?
AppShell.xaml中有趣的代码部分是:
<?xml version="1.0" encoding="UTF-8"?>
<Shell xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:retrogamez="clr-namespace:RetroGameZ"
Title="RetroGameZ"
x:Class="RetroGameZ.AppShell">
<Shell.Resources>
<ResourceDictionary>
<Style x:Key="BaseStyle" targettype="Element">
<Setter Property="Shell.BackgroundColor" Value="#049DBF" />
<Setter Property="Shell.ForegroundColor" Value="White" />
<Setter Property="Shell.TitleColor" Value="White" />
<Setter Property="Shell.disabledColor" Value="#03A6A6" />
<Setter Property="Shell.UnselectedColor" Value="#D3D3D3" />
<Setter Property="Shell.TabBarBackgroundColor" Value="#049DBF" />
<Setter Property="Shell.TabBarForegroundColor" Value="White"/>
<Setter Property="Shell.TabBarUnselectedColor" Value="#D3D3D3"/>
<Setter Property="Shell.TabBarTitleColor" Value="White"/>
</Style>
<Style targettype="TabBar" BasedOn="{StaticResource BaseStyle}" />
<Style targettype="FlyoutItem" BasedOn="{StaticResource BaseStyle}" />
</ResourceDictionary>
</Shell.Resources>
后来只有单个组件。
解决方法
找到适用于 Android 的解决方案:
在 MainActivity.cs
中,在 base.OnCreate()
之前,添加以下行:
AppCompatDelegate.DefaultNightMode = AppCompatDelegate.ModeNightNo;
,
假设您正在使用https://devblogs.microsoft.com/xamarin/app-themes-xamarin-forms/中提到的主题样式的Xamarin.Forms嵌入功能。
尝试在您的App.cs
App.Current.UserAppTheme = OSAppTheme.Light;
如果您未设置任何内容或已设置
App.Current.UserAppTheme = OSAppTheme.Unspecified;
它将遵循您当前的操作系统主题。
,我尝试了上述所有解决方案,但只有以下步骤对我有用。
- 打开
MainActivity.cs
并添加AppCompatDelegate.DefaultNightMode = AppCompatDelegate.ModeNightNo;
作为OnCreate
方法的第一行:
protected override void OnCreate(Bundle savedInstanceState)
{
AppCompatDelegate.DefaultNightMode = AppCompatDelegate.ModeNightNo;
base.OnCreate(savedInstanceState);
// ... other Xamarin stuff
}
- 打开
Resources/values/styles.xml
并添加行<item name="android:forceDarkAllowed">false</item>
:
<?xml version="1.0" encoding="utf-8" ?>
<resources>
<style name="MainTheme" parent="MainTheme.Base">
<!-- ... other Xamarin stuff -->
<item name="android:forceDarkAllowed">false</item>
<!-- ... other Xamarin stuff -->
</style>
</resources>