using System.ComponentModel; using System.Windows.Markup; namespace NeoUI.Appearance; /// /// 提供字典实现,其中包含组件和其他设备使用的主题资源。 /// [Localizability(LocalizationCategory.Ignore)] [Ambient] [UsableDuringInitialization(true)] public class ThemesDictionary : ResourceDictionary { /// /// 提供字典实现,其中包含组件和其他设备使用的主题资源。此字典能够根据当前应用程序的主题模式(如浅色或深色)自动加载相应的资源文件,并且在设计时会提供默认的静态主题以支持智能感知和可视化设计器。 /// /// /// 该类继承自,并扩展了特定于主题管理的功能。它通过检查是否处于设计模式来决定加载设计时专用资源还是运行时实际应用的主题资源。此外,还提供了设置当前主题模式的方法,允许动态切换应用的主题。 /// public ThemesDictionary() { // 2. 在构造函数的最开始检查是否处于设计模式 if (DesignerProperties.GetIsInDesignMode(new DependencyObject())) { // 如果是在设计器中,直接加载一个默认的、静态的主题文件 // 这就是专门给设计器和智能感知“看”的资源 // 这样,智能感知就能找到所有资源了 Source = new Uri($"{ThemeManager.ThemesDictionaryPath}Light.xaml", UriKind.Absolute); // 加载完设计时资源后,直接返回,不执行任何运行时的逻辑 return; } SetSourceBasedOnSelectedTheme(ThemeMode.Light); } private void SetSourceBasedOnSelectedTheme(ThemeMode? selectedApplicationTheme) { // 在运行时,我们不希望执行设计时逻辑,所以要再次检查 if (DesignerProperties.GetIsInDesignMode(new DependencyObject())) { return; } var themeName = selectedApplicationTheme switch { ThemeMode.Light => "Light", ThemeMode.Dark => "Dark", _ => "Light", }; Source = new Uri($"{ThemeManager.ThemesDictionaryPath}{themeName}.xaml", UriKind.Absolute); } /// /// 设置默认应用程序主题。 /// public ThemeMode Theme { set => SetSourceBasedOnSelectedTheme(value); } }