Ustawienie w Preferences
Dane aplikacji i czas: Preferences, pliki, zegar i daty - Aplikacje mobilne: .NET MAUI krok po kroku (maui)
Preferences.Default.Set("theme", "ciemny") zapisuje wartość pod kluczem, a Preferences.Default.Get("theme", "jasny") ją odczytuje (drugi argument to wartość, gdy klucza jeszcze nie ma). Przełącz motyw, kliknij Uruchom ponownie pod telefonem i zobacz, że wybór został.MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MauiApp1.MainPage"
Title="Motyw">
<VerticalStackLayout x:Name="Root" Padding="20" Spacing="15">
<HorizontalStackLayout Spacing="10">
<Switch x:Name="DarkSwitch" Toggled="OnDarkToggled"/>
<Label x:Name="ThemeLabel" VerticalOptions="Center" FontSize="20"/>
</HorizontalStackLayout>
</VerticalStackLayout>
</ContentPage>MainPage.xaml.cs
namespace MauiApp1
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
DarkSwitch.IsToggled = Preferences.Default.Get("theme", "jasny") == "ciemny";
ShowTheme();
}
private void OnDarkToggled(object sender, ToggledEventArgs e)
{
Preferences.Default.Set("theme", e.Value ? "ciemny" : "jasny");
ShowTheme();
}
private void ShowTheme()
{
string theme = Preferences.Default.Get("theme", "jasny");
ThemeLabel.Text = $"Motyw: {theme}";
Root.BackgroundColor = theme == "ciemny" ? Colors.DimGray : Colors.White;
}
}
}Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.
Wszystkie lekcje kursu Aplikacje mobilne: .NET MAUI krok po kroku·Zaloguj się, aby zapisać postęp na koncie.