|
@@ -0,0 +1,79 @@
|
|
|
|
|
+using System;
|
|
|
|
|
+using System.Collections.Generic;
|
|
|
|
|
+using System.Linq;
|
|
|
|
|
+using System.Text;
|
|
|
|
|
+using System.Threading.Tasks;
|
|
|
|
|
+using System.Windows;
|
|
|
|
|
+
|
|
|
|
|
+namespace SKMC.UI.Themes
|
|
|
|
|
+{
|
|
|
|
|
+ /// <summary>
|
|
|
|
|
+ /// 主题管理器
|
|
|
|
|
+ /// </summary>
|
|
|
|
|
+ public static class ThemeManager
|
|
|
|
|
+ {
|
|
|
|
|
+ private static readonly string ThemesPath = "pack://application:,,,/SKMC.UI;component/Themes/";
|
|
|
|
|
+ /// <summary>
|
|
|
|
|
+ /// 变更主题资源
|
|
|
|
|
+ /// </summary>
|
|
|
|
|
+ /// <param name="themeName"></param>
|
|
|
|
|
+ public static void ChangeTheme(string themeName)
|
|
|
|
|
+ {
|
|
|
|
|
+ // 获取应用程序资源
|
|
|
|
|
+ var appResources = Application.Current.Resources;
|
|
|
|
|
+ var mergedDictionaries = appResources.MergedDictionaries;
|
|
|
|
|
+
|
|
|
|
|
+ // 查找并移除旧的 Light/Dark 主题字典
|
|
|
|
|
+ var oldThemeDict = mergedDictionaries
|
|
|
|
|
+ .FirstOrDefault(d => d.Source != null &&
|
|
|
|
|
+ (d.Source.OriginalString.Contains("/Themes/Light.xaml") ||
|
|
|
|
|
+ d.Source.OriginalString.Contains("/Themes/Dark.xaml")));
|
|
|
|
|
+
|
|
|
|
|
+ if (oldThemeDict != null)
|
|
|
|
|
+ {
|
|
|
|
|
+ mergedDictionaries.Remove(oldThemeDict);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // 添加新的主题字典
|
|
|
|
|
+ var newThemeDict = new ResourceDictionary
|
|
|
|
|
+ {
|
|
|
|
|
+ Source = new Uri($"{ThemesPath}{themeName}.xaml", UriKind.Absolute)
|
|
|
|
|
+ };
|
|
|
|
|
+
|
|
|
|
|
+ // 插入到合适的位置(通常在 Colors.xaml 之前)
|
|
|
|
|
+ //var colorsDict = mergedDictionaries
|
|
|
|
|
+ // .FirstOrDefault(d => d.Source != null &&
|
|
|
|
|
+ // d.Source.OriginalString.Contains("/Assets/Colors.xaml"));
|
|
|
|
|
+
|
|
|
|
|
+ //if (colorsDict != null)
|
|
|
|
|
+ //{
|
|
|
|
|
+ // var index = mergedDictionaries.IndexOf(colorsDict);
|
|
|
|
|
+ // mergedDictionaries.Insert(index, newThemeDict);
|
|
|
|
|
+ //}
|
|
|
|
|
+ //else
|
|
|
|
|
+ //{
|
|
|
|
|
+ // mergedDictionaries.Add(newThemeDict);
|
|
|
|
|
+ //}
|
|
|
|
|
+ mergedDictionaries.Add(newThemeDict);
|
|
|
|
|
+ ForceRefreshResources();
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private static void ForceRefreshResources()
|
|
|
|
|
+ {
|
|
|
|
|
+ // 刷新所有窗口的资源
|
|
|
|
|
+ foreach (Window window in Application.Current.Windows)
|
|
|
|
|
+ {
|
|
|
|
|
+ window.InvalidateVisual();
|
|
|
|
|
+ window.UpdateLayout();
|
|
|
|
|
+ // 强制重新评估资源
|
|
|
|
|
+ var resources = window.Resources;
|
|
|
|
|
+ var merged = resources.MergedDictionaries;
|
|
|
|
|
+
|
|
|
|
|
+ foreach (var dict in merged)
|
|
|
|
|
+ {
|
|
|
|
|
+ dict.Source = dict.Source;
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+}
|