using System.ComponentModel; using System.Windows.Markup; namespace Melskin.Appearance; /// /// 提供字典实现,该字典通过合并一个“模式”字典和一个依赖于模式的“调色板”字典来动态构建完整的主题。 /// 此版本已根据指定的文件夹结构进行调整。 /// [Localizability(LocalizationCategory.Ignore)] [Ambient] [UsableDuringInitialization(true)] public class ThemesDictionary : ResourceDictionary { private readonly ResourceDictionary modeDictionary = new ResourceDictionary(); private readonly ResourceDictionary paletteDictionary = new ResourceDictionary(); private ThemeMode? currentMode; private ThemePalette? currentPalette; /// /// 构造函数,将内部字典添加到 MergedDictionaries 集合。 /// public ThemesDictionary() { MergedDictionaries.Add(modeDictionary); MergedDictionaries.Add(paletteDictionary); if (DesignerProperties.GetIsInDesignMode(new DependencyObject())) { UpdateSources(); } } /// /// 根据当前的 Mode 和 Palette 更新内部字典的 Source。 /// private void UpdateSources() { // 设计时模式:加载一个固定的、安全的主题组合以确保设计器稳定。 if (DesignerProperties.GetIsInDesignMode(new DependencyObject())) { // 加载 Mode 文件: .../Themes/Light.xaml var defaultModeUri = new Uri($"{ThemeManager.ThemesDictionaryPath}Light.xaml", UriKind.RelativeOrAbsolute); if (modeDictionary.Source != defaultModeUri) modeDictionary.Source = defaultModeUri; // 加载 Palette 文件: .../Themes/Accents/LightBlue.xaml var defaultPaletteUri = new Uri($"{ThemeManager.ThemesDictionaryPath}Accents/LightBlue.xaml", UriKind.RelativeOrAbsolute); if (paletteDictionary.Source != defaultPaletteUri) paletteDictionary.Source = defaultPaletteUri; return; } // 运行时模式:根据当前已有的属性值进行更新。 // 更新 Mode 字典 (只要 Mode 有值就更新) if (currentMode.HasValue) { // 路径示例: /Melskin;component/Appearance/Themes/Dark.xaml var modeSourceUri = new Uri($"{ThemeManager.ThemesDictionaryPath}{currentMode.Value}.xaml", UriKind.RelativeOrAbsolute); if (modeDictionary.Source != modeSourceUri) { modeDictionary.Source = modeSourceUri; } } // 更新 Palette 字典 (必须在 Mode 和 Palette 都有值的情况下才更新) if (currentMode.HasValue && currentPalette.HasValue) { var paletteName = $"{currentMode.Value}{currentPalette.Value}"; // 路径示例: /Melskin;component/Appearance/Themes/Accents/DarkGreen.xaml var paletteSourceUri = new Uri($"{ThemeManager.ThemesDictionaryPath}Accents/{paletteName}.xaml", UriKind.RelativeOrAbsolute); if (paletteDictionary.Source != paletteSourceUri) { paletteDictionary.Source = paletteSourceUri; } } } /// /// 设置应用程序的主题模式(明或暗)。 /// public ThemeMode Mode { set { if (currentMode != value) { currentMode = value; UpdateSources(); } } } /// /// 设置应用程序的主题调色板(颜色)。 /// public ThemePalette Palette { set { if (currentPalette != value) { currentPalette = value; UpdateSources(); } } } }