66 lines
2.1 KiB
C#
66 lines
2.1 KiB
C#
using System.Reflection;
|
|
|
|
namespace Phonebook.Services;
|
|
|
|
public enum AppThemeType { Green, Blue, Dark, Light }
|
|
|
|
public class ThemeService
|
|
{
|
|
private readonly Application _app;
|
|
private readonly string _prefsKey = "user_theme_preference";
|
|
|
|
private static readonly Dictionary<AppThemeType, string> ThemePaths = new()
|
|
{
|
|
{ AppThemeType.Green, "Themes/GreenTheme.xaml" },
|
|
{ AppThemeType.Blue, "Themes/BlueTheme.xaml" },
|
|
{ AppThemeType.Dark, "Themes/DarkTheme.xaml" },
|
|
{ AppThemeType.Light, "Themes/GreenTheme.xaml" }
|
|
};
|
|
|
|
public ThemeService()
|
|
{
|
|
_app = Application.Current ?? throw new NullReferenceException();
|
|
}
|
|
|
|
public AppThemeType CurrentTheme { get; private set; } = AppThemeType.Green;
|
|
|
|
public void LoadSavedTheme()
|
|
{
|
|
var saved = Preferences.Get(_prefsKey, string.Empty);
|
|
if (Enum.TryParse<AppThemeType>(saved, out var theme))
|
|
{
|
|
ApplyTheme(theme);
|
|
}
|
|
}
|
|
|
|
public async Task ApplyTheme(AppThemeType themeType)
|
|
{
|
|
if (!ThemePaths.TryGetValue(themeType, out var resourcePath))
|
|
return;
|
|
|
|
// Remove existing theme dictionary
|
|
var existing = _app.Resources.MergedDictionaries
|
|
.FirstOrDefault(d => d.Source?.OriginalString.Contains("Themes/") == true);
|
|
if (existing != null)
|
|
_app.Resources.MergedDictionaries.Remove(existing);
|
|
|
|
var newTheme = new ResourceDictionary();
|
|
|
|
await using var stream = await FileSystem.Current.OpenAppPackageFileAsync(resourcePath);
|
|
using var streamReader = new StreamReader(stream);
|
|
newTheme.LoadFromXaml(streamReader.ReadToEnd());
|
|
|
|
_app.Resources.MergedDictionaries.Add(newTheme);
|
|
|
|
CurrentTheme = themeType;
|
|
Preferences.Set(_prefsKey, themeType.ToString());
|
|
|
|
// Notify UI if needed
|
|
ThemeChanged?.Invoke(this, EventArgs.Empty);
|
|
}
|
|
|
|
public IEnumerable<AppThemeType> AvailableThemes =>
|
|
Enum.GetValues<AppThemeType>();
|
|
|
|
public event EventHandler? ThemeChanged;
|
|
} |