簡體   English   中英

如何在關閉時保存背景顏色

[英]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://learn.microsoft.com/en-us/xamarin/essentials/preferences?tabs=android

Resources中保存顏色,在使用 Button 的示例中,設置顏色為綠色或紅色。

在頂部的 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");
    }

也可以使用它來更改按鈕等的 TextColor,例如 PricipalColor。

StaticResource已設置,您可以更改DynamicResource

應用程序.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}" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM