我将通过布尔变量将 StaticResource 颜色作为 BackgroundColor 绑定到 Shell(在 AppShell.xaml 中)。我的解决方案不起作用。我总是得到默认的背景颜色(参见底部的样式)。我从来没有得到Yellow100或Gray500。 错误在哪里呢?
<Shell ...
xmlns:viewModels="clr-namespace:MyApp.ViewModels"
x:DataType="viewModels:AppShellViewModel"
BackgroundColor="{Binding IsOnline, Converter={StaticResource BoolToColorConverter}}" >
<Shell.Resources>
<ResourceDictionary>
<toolkit:IsStringNotNullOrEmptyConverter x:Key="IsStringNotNullOrEmptyConverter" />
<toolkit:BoolToObjectConverter x:Key="BoolToColorConverter" TrueObject="{StaticResource Yellow100}" FalseObject="{StaticResource Gray500}" />
</ResourceDictionary>
</Shell.Resources>
我还尝试使用x:TypeArguments="Color"或x:DataType="Color"
我的视图模型:
public partial class AppShellViewModel : ObservableObject
{
[ObservableProperty]
private bool _isOnline;
public AppShellViewModel(ConnectionStateService connectionStateService)
{
IsOnline = connectionStateService.IsOnline();
}
}
我的颜色.xaml
<ResourceDictionary
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
<Color x:Key="Gray500">#6E6E6E</Color>
<Color x:Key="Yellow100">#F7B548</Color>
我尝试过这个并且效果很好:
BackgroundColor="{StaticResource Yellow100Accent}"
默认颜色是通过 Styles.xaml 中的 Style 设置的:
<Style TargetType="Shell" ApplyToDerivedTypes="True">
<Setter Property="Shell.BackgroundColor"
Value="{AppThemeBinding Light={StaticResource Primary}, Dark={StaticResource Gray950}}" /> ...
AppShell.xaml.cs:
public partial class AppShell
{
private readonly AppShellViewModel _appShellViewModel;
public AppShell(AppShellViewModel appShellAppShellViewModel)
{
_appShellViewModel = appShellAppShellViewModel;
BindingContext = _appShellViewModel;
InitializeComponent();
Routing.RegisterRoute(nameof(FirstPage), typeof(FirstPage));
Routing.RegisterRoute(
...
} ....
数据触发器可能是更好的选择: