mirror of
https://github.com/PacktPublishing/Learn-WinUI-3-Second-Edition.git
synced 2026-06-20 12:23:09 +00:00
Add chapter 10 sample project
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
using Microsoft.UI.Xaml;
|
||||
|
||||
using TemplateStudioSampleApp.Contracts.Services;
|
||||
using TemplateStudioSampleApp.Helpers;
|
||||
|
||||
namespace TemplateStudioSampleApp.Services;
|
||||
|
||||
public class ThemeSelectorService : IThemeSelectorService
|
||||
{
|
||||
private const string SettingsKey = "AppBackgroundRequestedTheme";
|
||||
|
||||
public ElementTheme Theme { get; set; } = ElementTheme.Default;
|
||||
|
||||
private readonly ILocalSettingsService _localSettingsService;
|
||||
|
||||
public ThemeSelectorService(ILocalSettingsService localSettingsService)
|
||||
{
|
||||
_localSettingsService = localSettingsService;
|
||||
}
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
Theme = await LoadThemeFromSettingsAsync();
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
public async Task SetThemeAsync(ElementTheme theme)
|
||||
{
|
||||
Theme = theme;
|
||||
|
||||
await SetRequestedThemeAsync();
|
||||
await SaveThemeInSettingsAsync(Theme);
|
||||
}
|
||||
|
||||
public async Task SetRequestedThemeAsync()
|
||||
{
|
||||
if (App.MainWindow.Content is FrameworkElement rootElement)
|
||||
{
|
||||
rootElement.RequestedTheme = Theme;
|
||||
|
||||
TitleBarHelper.UpdateTitleBar(Theme);
|
||||
}
|
||||
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task<ElementTheme> LoadThemeFromSettingsAsync()
|
||||
{
|
||||
var themeName = await _localSettingsService.ReadSettingAsync<string>(SettingsKey);
|
||||
|
||||
if (Enum.TryParse(themeName, out ElementTheme cacheTheme))
|
||||
{
|
||||
return cacheTheme;
|
||||
}
|
||||
|
||||
return ElementTheme.Default;
|
||||
}
|
||||
|
||||
private async Task SaveThemeInSettingsAsync(ElementTheme theme)
|
||||
{
|
||||
await _localSettingsService.SaveSettingAsync(SettingsKey, theme.ToString());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user