WIn_RustTools/RustTools/Services/ThemeSelectorService.cs

64 lines
1.6 KiB
C#
Raw Permalink Normal View History

2024-07-14 11:24:10 +00:00
using Microsoft.UI.Xaml;
using RustTools.Contracts.Services;
using RustTools.Helpers;
namespace RustTools.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());
}
}