using System; using System.Collections.ObjectModel; using System.Windows; namespace PersonalToolBox.Helpers; /// /// 主题切换辅助类,动态替换 Application 的 ResourceDictionary /// public static class ThemeHelper { private const string ThemePrefix = "Themes/"; private const string DarkThemePath = "Themes/DarkTheme.xaml"; private const string LightThemePath = "Themes/LightTheme.xaml"; /// /// 切换主题(Dark / Light) /// public static void ApplyTheme(string theme) { var app = Application.Current; if (app == null) return; // 移除旧的主题资源字典 var oldDict = FindThemeDictionary(app.Resources.MergedDictionaries); if (oldDict != null) app.Resources.MergedDictionaries.Remove(oldDict); // 加载新的主题资源字典 var path = theme switch { "Light" => LightThemePath, _ => DarkThemePath }; var newDict = new ResourceDictionary { Source = new Uri(path, UriKind.Relative) }; app.Resources.MergedDictionaries.Add(newDict); } /// /// 在当前合并字典中查找主题相关的 ResourceDictionary /// private static ResourceDictionary? FindThemeDictionary(Collection dictionaries) { foreach (var dict in dictionaries) { if (dict.Source != null && dict.Source.OriginalString.StartsWith(ThemePrefix)) return dict; } return null; } }