如何在关闭时保存背景颜色

How to save background color on close

我正在用 Xamarin Forms 做一个 android 游戏,在这个游戏中你可以选择主题是深色还是浅色。我所做的是在 App.xmal.

中创建静态资源(颜色)
<Application.Resources>

    <Color x:Key="PrincipalColor" >#181818</Color>
    <Color x:Key="PrincipalColorInvert" >#ffffff</Color>

</Application.Resources>

但是当用户更改主题(staticressources 颜色)并退出游戏时,它不会保存他的首选项。我听说过“App.Current.Properties["Id"] = ...”,但我想不通。如果有人知道该怎么做,我会很高兴知道。 谢谢。

您可以使用Xamarin.Essentials: Preferences

https://docs.microsoft.com/en-us/xamarin/essentials/preferences?tabs=android

Resources 中保存颜色,在带有按钮的示例中,设置颜色为绿色或红色。

在MainPage.xaml顶部

BackgroundColor="{DynamicResource defaultBackgroundColor}"

然后是按钮

  <Button Clicked="Button_Clicked" Text="Green" />

    <Button Clicked="Button_Clicked_1" Text="Red" />

在MainPage.xaml.cs using Xamarin.Essentials;

 public MainPage()
    {
        InitializeComponent();
        App.Current.Resources["defaultButtonBackgroundColor"] = Preferences.Get("defaultButtonBackgroundColor", "Blue");
    }

    private void Button_Clicked(object sender, EventArgs e)
    {
        Preferences.Set("BackgroundColor", "Green");
        App.Current.Resources["defaultBackgroundColor"] = Preferences.Get("BackgroundColor", "Blue");
    }

    private void Button_Clicked_1(object sender, EventArgs e)
    {
        Preferences.Set("BackgroundColor", "Red");
        App.Current.Resources["defaultBackgroundColor"] = Preferences.Get("BackgroundColor", "Blue");
    }

也可以用它来改变 Button 等的 TextColor,例如 PricipalColor。

StaticResource 已设置,DynamicResource 您可以更改

App.xaml.cs

    <Application.Resources>

    <Color x:Key="PrincipalColor" >#181818</Color>

</Application.Resources>

MainPage.xaml.cs

   public MainPage()
    {
        InitializeComponent();
        App.Current.Resources["defaultButtonBackgroundColor"] = Preferences.Get("defaultButtonBackgroundColor", "Blue");
        App.Current.Resources["PrincipalColor"] = Preferences.Get("PrincipalColor", "#181818");
    }

使用 Button 将 PrincipalColor 更改为白色或任何其他颜色。

 private void Button_Clicked(object sender, EventArgs e)
    {
        Preferences.Set("PrincipalColor", "White");
        App.Current.Resources["PrincipalColor"] = Preferences.Get("PrincipalColor", "#181818");
    }

MainPage.xaml 在第一个 Button 中是 Static 而 2e Dynamic 改变了 TextColor

<Button Clicked="Button_Clicked" Text="Green" TextColor="{StaticResource PrincipalColor}" />

    <Button Clicked="Button_Clicked_1" Text="Red" TextColor="{DynamicResource PrincipalColor}" />