Files
Ayay/SHH.CameraDashboard/Core/ThemeManager.cs

92 lines
2.8 KiB
C#
Raw Normal View History

2026-01-01 22:40:32 +08:00
using System.Windows;
namespace SHH.CameraDashboard
{
public static class ThemeManager
{
// 使用字典Key=主题名, Value=路径
private static readonly Dictionary<string, string> _themeMap = new Dictionary<string, string>
{
{ "Dark", "/Style/Themes/Colors.Dark.xaml" },
{ "Light", "/Style/Themes/Colors.Light.xaml" },
// { "Blue", "/Style/Themes/Colors.Blue.xaml" }
};
// 当前主题名称
public static string CurrentThemeName { get; private set; } = "Dark";
/// <summary>
/// 指定切换到某个主题
/// </summary>
/// <param name="themeName">主题名称 (Dark, Light...)</param>
public static void SetTheme(string themeName)
{
if (!_themeMap.ContainsKey(themeName))
{
System.Diagnostics.Debug.WriteLine($"未找到主题: {themeName}");
return;
}
ApplyTheme(_themeMap[themeName]);
CurrentThemeName = themeName;
}
/// <summary>
/// 循环切换下一个主题 (保留旧功能)
/// </summary>
public static void SwitchToNextTheme()
{
// 获取所有 Key 的列表
var keys = _themeMap.Keys.ToList();
// 找到当前 Key 的索引
int index = keys.IndexOf(CurrentThemeName);
// 计算下一个索引
index++;
if (index >= keys.Count) index = 0;
// 切换
SetTheme(keys[index]);
}
/// <summary>
/// 私有方法:执行具体的资源替换
/// </summary>
private static void ApplyTheme(string themePath)
{
var appResources = Application.Current.Resources;
ResourceDictionary oldDict = null;
// 查找旧的皮肤字典
foreach (var dict in appResources.MergedDictionaries)
{
if (dict.Source != null && dict.Source.OriginalString.Contains("/Themes/Colors."))
{
oldDict = dict;
break;
}
}
// 移除旧的
if (oldDict != null)
{
appResources.MergedDictionaries.Remove(oldDict);
}
// 加载新的
try
{
var newDict = new ResourceDictionary
{
Source = new Uri(themePath, UriKind.Relative)
};
appResources.MergedDictionaries.Add(newDict);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"加载主题文件失败: {ex.Message}");
}
}
}
}