Files
ShrlAlgoToolkit/Melskin/Appearance/ThemeManager.cs

644 lines
30 KiB
C#
Raw Normal View History

using System.Collections;
using System.Diagnostics;
using System.IO;
2025-08-24 13:49:55 +08:00
using System.Reflection;
using System.Windows.Media.Animation;
2026-01-02 17:30:41 +08:00
namespace Melskin.Appearance
2025-08-24 13:49:55 +08:00
{
/// <summary>
/// 统一主题管理(合并原 ThemeManager + AppearanceManager 功能)。
/// 功能点:
/// 1. 维护当前明暗模式 / 调色板缓存与事件
/// 2. 提供异步/同步切换(含可选动画)
/// 3. 动画策略:先交换字典(保证新增键立即可用)再对所有可动画 SolidColorBrush 做颜色补间(含新增键过渡)
/// 4. 只允许同时存在一个主题字典 + 一个调色板字典(顺序:主题 -> 调色板 -> 其它)
/// 5. 可选持久化
/// 兼容:保留旧 API (ApplyThemeMode / ApplyThemePalette / SwitchThemeMode 等)
///
/// 设计要点:
/// - “主题”与“调色板”被拆成两个 ResourceDictionary顺序控制保证覆盖链正确。
/// - 动画采用“字典快速替换 + 颜色补间”而不是实时动态更新键值,确保资源引用立即可见且减少闪烁。
/// - AnimatableBrushKeys 只跟踪 SolidColorBrush 键(避免对非 Brush / 冻结 Freezable 执行动画引发异常)。
/// - 使用 Dispatcher 保障在 UI 线程执行所有 WPF 资源操作。
/// - 同步 API 内部通过 DispatcherFrame 等待异步完成(避免外部 async 污染,同时保持阻塞式调用语义)。
/// </summary>
public class ThemeManager
{
/// <summary>
/// 获取当前程序集的命名空间名称该属性返回一个字符串表示包含ThemeManager类的程序集的名称。
/// </summary>
/// <remarks>
/// 该属性用于获取应用程序的命名空间,以便在构建资源路径或其他需要引用程序集名称的地方使用。例如,在定位主题字典路径或着色器文件时,`LibraryNamespace`提供了必要的程序集名称信息。
/// </remarks>
public static string LibraryNamespace => Assembly.GetExecutingAssembly().GetName().Name!;
2025-08-24 13:49:55 +08:00
/// <summary>
/// 获取主题字典的基路径该路径用于定位应用程序中的主题资源文件。此属性返回一个字符串表示到主题资源文件夹的包URI。
/// </summary>
/// <remarks>
2025-12-23 21:35:54 +08:00
/// 该属性通常被用于构建指向具体主题样式或颜色调色板文件的完整路径。例如,它可用于加载位于`Themes/`目录下的不同主题模式如Light.xaml, Dark.xaml或颜色调色板文件如Accents/LightBlue.xaml。通过使用`ThemesDictionaryPath`作为基础路径,可以方便地访问和应用不同的主题设置。
2025-08-24 13:49:55 +08:00
/// </remarks>
public static string ThemesDictionaryPath => $"pack://application:,,,/{LibraryNamespace};component/Themes/";
private static bool _persistenceEnabled;
/// <summary>
/// 当应用程序的主题模式发生变化时触发的事件。此事件允许订阅者在主题模式更改时执行特定的操作。
/// </summary>
/// <remarks>
/// 该事件通常在调用改变主题模式的方法如ApplyThemeMode或SwitchThemeMode后被触发。通过注册此事件开发者可以监听到主题模式的变化并根据需要更新UI或其他逻辑。
/// </remarks>
public static event Action<ThemeMode>? ThemeModeChanged;
/// <summary>
/// 当应用程序的主题调色板发生变化时触发的事件。此事件允许订阅者在主题调色板更改时执行特定操作。
/// </summary>
/// <remarks>
/// 该事件通常用于通知UI组件或其他依赖于当前主题调色板的服务以便它们可以相应地更新其外观或行为。每当通过`ApplyTheme`、`ApplyThemePalette`等方法改变主题调色板时,都会触发此事件,并传递新的`ThemePalette`作为参数给所有注册的处理程序。
/// </remarks>
public static event Action<ThemePalette>? ThemePaletteChanged;
private static readonly IEasingFunction ThemeEasing = new CubicEase { EasingMode = EasingMode.EaseInOut };
#region Animatable Keys
private static readonly object KeyLock = new();
private static List<string> _animatableBrushKeys = [];
private static IReadOnlyList<string> AnimatableBrushKeys
{
get { lock (KeyLock) return [.. _animatableBrushKeys]; }
2025-08-24 13:49:55 +08:00
}
private static void RefreshAnimatableKeysFromCurrentManagedDictionaries(ResourceDictionary root, bool merge = false)
{
var keys = new HashSet<string>(StringComparer.Ordinal);
if (merge)
{
lock (KeyLock)
{
foreach (var k in _animatableBrushKeys)
keys.Add(k);
}
}
foreach (var dict in root.MergedDictionaries.Where(IsManagedThemeDictionary))
{
foreach (var key in dict.Keys.OfType<object>())
{
2026-01-02 16:37:37 +08:00
if (dict[key] is SolidColorBrush)
2025-08-24 13:49:55 +08:00
keys.Add(key.ToString());
}
}
lock (KeyLock)
{
_animatableBrushKeys = [.. keys];
2025-08-24 13:49:55 +08:00
}
}
private static Dictionary<string, Color> TakeColorSnapshot(ResourceDictionary resources)
{
var snapshot = new Dictionary<string, Color>(StringComparer.Ordinal);
foreach (var key in AnimatableBrushKeys)
{
var brush = FindBrushInManagedDictionaries(resources, key);
2025-08-26 21:33:20 +08:00
2025-08-24 13:49:55 +08:00
if (brush != null)
snapshot[key] = brush.Color;
}
return snapshot;
}
private static SolidColorBrush? FindBrushInManagedDictionaries(ResourceDictionary root, string key)
{
foreach (var d in root.MergedDictionaries.Where(IsManagedThemeDictionary))
{
if (d.Contains(key) && d[key] is SolidColorBrush b)
return b;
}
return null;
}
private static bool IsManagedThemeDictionary(ResourceDictionary dict)
{
var src = dict.Source?.OriginalString;
if (string.IsNullOrEmpty(src)) return false;
2025-12-23 21:35:54 +08:00
if (src?.IndexOf("/Accents/", StringComparison.OrdinalIgnoreCase) >= 0)
2025-08-24 13:49:55 +08:00
return true;
var fileName = Path.GetFileName(src);
return fileName != null &&
(fileName.Equals("Light.xaml", StringComparison.OrdinalIgnoreCase) ||
fileName.Equals("Dark.xaml", StringComparison.OrdinalIgnoreCase));
}
private static Task AnimateToNewTheme(ResourceDictionary resources,
Dictionary<string, Color> fromColors,
2025-08-24 13:49:55 +08:00
int baseDurationMs)
{
var tasks = new List<Task>();
foreach (var dict in resources.MergedDictionaries.Where(IsManagedThemeDictionary).ToList())
{
foreach (var keyObj in dict.Keys.OfType<object>().ToList())
{
var key = keyObj?.ToString();
if (key == null) continue;
if (!AnimatableBrushKeys.Contains(key)) continue;
if (dict[key] is not SolidColorBrush brush) continue;
var toColor = brush.Color;
if (!fromColors.TryGetValue(key, out var fromColor))
fromColor = Color.FromArgb(0, toColor.R, toColor.G, toColor.B);
if (toColor == fromColor) continue;
Debug.WriteLine($"Animate Key: {key} from {fromColor} to {toColor}");
2025-08-24 13:49:55 +08:00
if (brush.IsFrozen)
{
// 冻结的 Brush 无法动画,需要复制一个新的
brush = brush.Clone();
dict[key] = brush; // 用可写的克隆体替换
}
// 设置初始色,然后异步补间到目标色
brush.Color = fromColor;
tasks.Add(AnimateBrushColorAsync(brush, toColor, baseDurationMs));
}
}
return Task.WhenAll(tasks);
}
/// <summary>
/// 【核心修改】针对单个 Brush 的颜色动画封装在Completed事件中捕获异常。
/// </summary>
private static Task<bool> AnimateBrushColorAsync(SolidColorBrush brush, Color toColor, int durationMs)
2025-08-24 13:49:55 +08:00
{
var tcs = new TaskCompletionSource<bool>();
if (brush.IsFrozen)
{
tcs.SetResult(true);
return tcs.Task;
}
var animation = new ColorAnimation
{
To = toColor,
Duration = TimeSpan.FromMilliseconds(durationMs),
EasingFunction = ThemeEasing,
FillBehavior = FillBehavior.Stop
2025-08-24 13:49:55 +08:00
};
animation.Completed += (_, _) =>
{
// 这是最关键的地方我们用try-catch包围了可能失败的操作
try
{
// 尝试移除动画并固化最终颜色
brush.BeginAnimation(SolidColorBrush.ColorProperty, null);
brush.Color = toColor;
}
catch (InvalidOperationException)
{
// 异常被预料并捕获。
// 此时动画已播放完毕虽然固化失败但因ResourceDictionary已切换UI最终状态正确。
// 我们安全地忽略这个异常,不让程序崩溃。
}
finally
{
// 无论成功还是失败都通知Task已完成。
tcs.TrySetResult(true);
}
};
brush.BeginAnimation(SolidColorBrush.ColorProperty, animation);
return tcs.Task;
}
#endregion
#region Public Query
/// <summary>
/// 获取当前应用程序的主题模式。
/// </summary>
/// <returns>返回当前应用的主题模式,可能的值为 Light 或 Dark。</returns>
public static ThemeMode GetAppThemeMode()
{
var dict = Current.Resources.MergedDictionaries
2025-08-24 13:49:55 +08:00
.FirstOrDefault(d => d.Source != null && (d.Source.OriginalString.EndsWith("light.xaml", StringComparison.OrdinalIgnoreCase)
|| d.Source.OriginalString.EndsWith("dark.xaml", StringComparison.OrdinalIgnoreCase)));
if (dict?.Source != null)
{
var s = dict.Source.OriginalString;
if (s.EndsWith("light.xaml", StringComparison.OrdinalIgnoreCase))
ActiveThemeMode = ThemeMode.Light;
2025-08-24 13:49:55 +08:00
else if (s.EndsWith("dark.xaml", StringComparison.OrdinalIgnoreCase))
ActiveThemeMode = ThemeMode.Dark;
2025-08-24 13:49:55 +08:00
}
return ActiveThemeMode;
2025-08-24 13:49:55 +08:00
}
/// <summary>
/// 获取应用程序当前使用的主题调色板。
/// </summary>
/// <returns>返回当前激活的主题调色板类型为ThemePalette枚举。</returns>
public static ThemePalette GetAppThemePalette()
{
var dict = Current.Resources.MergedDictionaries
2025-12-23 21:35:54 +08:00
.FirstOrDefault(d => d.Source != null && d.Source.OriginalString.IndexOf("/Accents/", StringComparison.OrdinalIgnoreCase) >= 0);
2025-08-24 13:49:55 +08:00
if (dict?.Source != null)
{
var s = Path.GetFileNameWithoutExtension(dict.Source.OriginalString);
if (s.EndsWith("Blue", StringComparison.OrdinalIgnoreCase)) ActiveThemePalette = ThemePalette.Blue;
else if (s.EndsWith("Green", StringComparison.OrdinalIgnoreCase)) ActiveThemePalette = ThemePalette.Green;
else if (s.EndsWith("Purple", StringComparison.OrdinalIgnoreCase)) ActiveThemePalette = ThemePalette.Purple;
2025-08-24 13:49:55 +08:00
}
return ActiveThemePalette;
2025-08-24 13:49:55 +08:00
}
#endregion
#region Apply Resources To Element
/// <summary>
/// 将应用程序级别的资源应用到指定的 FrameworkElement 上。
/// </summary>
/// <param name="frameworkElement">要应用资源的 FrameworkElement。</param>
public static void ApplyResourcesToElement(FrameworkElement frameworkElement)
{
if (frameworkElement == null) return;
var appMerged = Current.Resources.MergedDictionaries;
var target = frameworkElement.Resources.MergedDictionaries;
if (target.Count < appMerged.Count)
{
foreach (var d in appMerged)
if (!target.Contains(d))
target.Add(d);
}
}
#endregion
#region Unified Theme API (Async)
/// <summary>
/// 【核心功能】应用指定的主题模式和调色板,支持动画过渡。
/// </summary>
/// <param name="mode">可选参数,指定主题模式(浅色、深色或系统默认)。</param>
/// <param name="palette">可选参数,指定主题调色板(天蓝、墨绿或浅紫)。</param>
/// <param name="animate">布尔值,指示是否启用动画过渡效果。</param>
/// <param name="animationDurationMs">整数表示动画持续时间毫秒默认为350毫秒。</param>
/// <returns>返回一个Task对象代表异步操作的完成状态。</returns>
public static Task ApplyThemeAsync(ThemeMode? mode = null,
ThemePalette? palette = null,
bool animate = true,
2025-08-24 13:49:55 +08:00
int animationDurationMs = 350)
=> InternalApplyThemeAsync(mode, palette, animate, animationDurationMs);
/// <summary>
/// 应用指定的主题模式和调色板,可以选择是否进行动画过渡。
/// </summary>
/// <param name="mode">可选参数指定要应用的主题模式浅色、深色或系统默认。如果为null则使用当前设置。</param>
/// <param name="palette">可选参数指定要应用的主题调色板。如果为null则使用当前设置。</param>
/// <param name="animate">布尔值指示主题更改时是否应带有动画效果。默认为false。</param>
/// <param name="animationDurationMs">整数指定动画持续时间毫秒。仅当animate为true时有效默认值为350毫秒。</param>
public static void ApplyTheme(ThemeMode? mode = null,
ThemePalette? palette = null,
bool animate = false,
int animationDurationMs = 350)
{
var task = InternalApplyThemeAsync(mode, palette, animate, animationDurationMs);
// 如果在UI线程使用DispatcherFrame等待避免死锁
if (Application.Current?.Dispatcher.CheckAccess() == true && !task.IsCompleted)
{
var frame = new System.Windows.Threading.DispatcherFrame();
task.ContinueWith(_ => frame.Continue = false, TaskScheduler.FromCurrentSynchronizationContext());
System.Windows.Threading.Dispatcher.PushFrame(frame);
}
task.GetAwaiter().GetResult(); // 确保任何异常都能被抛出
}
private static async Task InternalApplyThemeAsync(ThemeMode? mode,
ThemePalette? palette,
bool animate,
int durationMs)
{
if (Application.Current?.Dispatcher == null) return;
if (!Application.Current.Dispatcher.CheckAccess())
{
await Application.Current.Dispatcher.InvokeAsync(
() => InternalApplyThemeAsync(mode, palette, animate, durationMs));
return;
}
var currentMode = GetAppThemeMode();
var currentPalette = GetAppThemePalette();
var newMode = mode ?? currentMode;
var newPalette = palette ?? currentPalette;
bool modeChanged = newMode != currentMode;
bool paletteChanged = newPalette != currentPalette || modeChanged;
if (!modeChanged && !paletteChanged) return;
var appResources = Current.Resources;
2025-08-26 21:33:20 +08:00
Dictionary<string, Color>? fromColors = null;
if (animate)
2025-08-24 13:49:55 +08:00
{
RefreshAnimatableKeysFromCurrentManagedDictionaries(appResources, merge: false);
fromColors = TakeColorSnapshot(appResources);
}
2025-08-24 13:49:55 +08:00
string modeName = newMode == ThemeMode.Dark ? "Dark" : "Light";
string paletteName = newPalette.ToString();
var themeUri = new Uri($"{ThemesDictionaryPath}{modeName}.xaml", UriKind.Absolute);
2025-12-23 21:35:54 +08:00
var paletteUri = new Uri($"{ThemesDictionaryPath}Accents/{modeName}{paletteName}.xaml", UriKind.Absolute);
2025-08-24 13:49:55 +08:00
if (modeChanged) ReplaceOrAddDictionary(themeUri, isTheme: true);
if (paletteChanged) ReplaceOrAddDictionary(paletteUri, isTheme: false);
2025-08-24 13:49:55 +08:00
if (animate && fromColors != null)
2025-08-24 13:49:55 +08:00
{
RefreshAnimatableKeysFromCurrentManagedDictionaries(appResources, merge: true);
await AnimateToNewTheme(appResources, fromColors, durationMs).ConfigureAwait(true);
2025-08-24 13:49:55 +08:00
}
if (modeChanged)
2025-08-24 13:49:55 +08:00
{
ActiveThemeMode = newMode;
ThemeModeChanged?.Invoke(newMode);
}
if (paletteChanged)
{
ActiveThemePalette = newPalette;
ThemePaletteChanged?.Invoke(newPalette);
2025-08-24 13:49:55 +08:00
}
if (_persistenceEnabled && (modeChanged || paletteChanged))
2025-08-24 13:49:55 +08:00
{
try { ThemePreferenceStore.Save(ActiveThemeMode, ActiveThemePalette); }
catch { /* 持久化失败静默 */ }
2025-08-24 13:49:55 +08:00
}
}
private static bool IsThemeDict(ResourceDictionary d)
{
var s = d.Source?.ToString();
return s != null &&
s.IndexOf("/Themes/", StringComparison.OrdinalIgnoreCase) >= 0 &&
2025-12-23 21:35:54 +08:00
s.IndexOf("/Accents/", StringComparison.OrdinalIgnoreCase) < 0 &&
(s.EndsWith("Light.xaml", StringComparison.OrdinalIgnoreCase) ||
s.EndsWith("Dark.xaml", StringComparison.OrdinalIgnoreCase));
}
private static bool IsPaletteDict(ResourceDictionary d)
{
var s = d.Source?.ToString();
2025-12-23 21:35:54 +08:00
return s != null && s.IndexOf("/Themes/Accents/", StringComparison.OrdinalIgnoreCase) >= 0;
}
private static void ReplaceOrAddDictionary(Uri uri, bool isTheme)
{
var merged = Current.Resources.MergedDictionaries;
2025-08-24 13:49:55 +08:00
if (isTheme)
{
for (int i = merged.Count - 1; i >= 0; i--)
if (IsThemeDict(merged[i])) merged.RemoveAt(i);
int firstPaletteIndex = -1;
for (int i = 0; i < merged.Count; i++)
if (IsPaletteDict(merged[i])) { firstPaletteIndex = i; break; }
var newTheme = new ResourceDictionary { Source = uri };
if (firstPaletteIndex >= 0)
merged.Insert(firstPaletteIndex, newTheme);
else
merged.Add(newTheme);
}
else
{
for (int i = merged.Count - 1; i >= 0; i--)
if (IsPaletteDict(merged[i])) merged.RemoveAt(i);
int themeIndex = -1;
for (int i = 0; i < merged.Count; i++)
if (IsThemeDict(merged[i])) { themeIndex = i; break; }
var newPalette = new ResourceDictionary { Source = uri };
if (themeIndex >= 0 && themeIndex + 1 <= merged.Count)
merged.Insert(themeIndex + 1, newPalette);
else
merged.Add(newPalette);
}
}
#endregion
#region Backward Compatible APIs
/// <summary>
/// 应用指定的主题调色板。
/// </summary>
/// <param name="themePalette">要应用的主题调色板。</param>
public static void ApplyThemePalette(ThemePalette themePalette) => ApplyTheme(null, themePalette, false);
/// <summary>
/// 【核心修改】根据给定的主题模式应用主题,不包括调色板的更改。
/// </summary>
/// <param name="themeMode">要应用的主题模式Light、Dark或System。</param>
public static void ApplyThemeMode(ThemeMode themeMode) => ApplyTheme(themeMode, null, false);
/// <summary>
/// 切换应用程序的主题模式。如果当前主题是亮色模式,则切换到暗色模式;如果当前主题是暗色模式,则切换到亮色模式。
/// </summary>
public static void SwitchThemeMode()
{
var target = GetAppThemeMode() == ThemeMode.Light ? ThemeMode.Dark : ThemeMode.Light;
ApplyTheme(target, ActiveThemePalette, false);
2025-08-24 13:49:55 +08:00
}
/// <summary>
/// 【核心功能】以动画方式切换当前应用的主题模式(亮/暗)。
/// </summary>
/// <param name="durationMs">动画持续时间单位为毫秒默认值为350毫秒。</param>
/// <returns>返回一个表示异步操作的任务。</returns>
public static Task SwitchThemeModeAnimatedAsync(int durationMs = 350)
{
var target = GetAppThemeMode() == ThemeMode.Light ? ThemeMode.Dark : ThemeMode.Light;
return ApplyThemeAsync(target, ActiveThemePalette, true, durationMs);
2025-08-24 13:49:55 +08:00
}
/// <summary>
/// 切换当前应用程序的主题模式,并使用动画效果。默认情况下,如果当前主题模式为浅色,则切换到深色模式;反之亦然。
/// </summary>
/// <param name="durationMs">动画持续时间以毫秒为单位默认值为350毫秒。</param>
public static void SwitchThemeModeAnimated(int durationMs = 350)
{
var target = GetAppThemeMode() == ThemeMode.Light ? ThemeMode.Dark : ThemeMode.Light;
ApplyTheme(target, ActiveThemePalette, true, durationMs);
2025-08-24 13:49:55 +08:00
}
/// <summary>
/// 【异步主题应用】根据给定的主题模式和调色板异步应用主题,并带有动画效果。
/// </summary>
/// <param name="mode">要应用的主题模式,如浅色、深色或跟随系统。</param>
/// <param name="palette">要应用的主题调色板,例如天蓝、墨绿等。</param>
/// <param name="durationMs">动画持续时间毫秒默认为350毫秒。</param>
/// <returns>返回一个表示异步操作的任务。</returns>
public static Task ApplyThemeAnimatedAsync(ThemeMode mode, ThemePalette palette, int durationMs = 350)
=> ApplyThemeAsync(mode, palette, true, durationMs);
#endregion
#region Persistence
/// <summary>
/// 【启用持久化】允许主题设置在应用会话之间保持不变。
/// </summary>
2025-08-24 13:49:55 +08:00
public static void EnablePersistence() => _persistenceEnabled = true;
/// <summary>
/// 【功能描述】禁用主题持久化功能。调用此方法后,将不会保存当前的主题设置到持久化存储中。
/// </summary>
2025-08-24 13:49:55 +08:00
public static void DisablePersistence() => _persistenceEnabled = false;
/// <summary>
/// 【功能】从持久化存储中恢复上次设置的主题模式和调色板,并应用到应用程序。
/// 该方法尝试从持久化存储中加载主题模式和调色板,如果成功则应用这些设置。在应用过程中临时禁用主题设置的持久化以避免循环保存。
/// </summary>
public static void RestorePersistedTheme()
{
// 此处应包含您自己的持久化加载逻辑
if (ThemePreferenceStore.TryLoad(out var mode, out var palette) && (mode.HasValue || palette.HasValue))
{
var was = _persistenceEnabled;
_persistenceEnabled = false;
try { ApplyTheme(mode, palette, animate: false); }
finally { _persistenceEnabled = was; }
}
}
#endregion
#region Debug
#if DEBUG
private static void DumpMerged(string tag)
{
System.Diagnostics.Debug.WriteLine($"==== {tag} MergedDictionaries ====");
2025-08-24 13:49:55 +08:00
int i = 0;
foreach (var d in Current.Resources.MergedDictionaries)
2025-08-24 13:49:55 +08:00
System.Diagnostics.Debug.WriteLine($"{i++}: {d.Source}");
}
#endif
#endregion
#region UiApplication
private static ThemeManager? _themeManagerInstance;
private readonly Application? application;
private Window? mainWindow;
private ResourceDictionary? resources;
2025-08-26 21:33:20 +08:00
private static bool ApplicationHasResources(Application application)
{
return application
.Resources.MergedDictionaries
.Where(e => e.Source is not null)
.Any(e => e.Source.ToString().Contains(LibraryNamespace));
}
/// <summary>
/// 是否绑定到一个有效的 Application 实例。
/// </summary>
public bool IsApplication => application is not null;
2025-08-24 13:49:55 +08:00
private ThemeManager(Application? application)
{
2025-08-26 21:33:20 +08:00
if (application is null)
{
return;
}
if (!ApplicationHasResources(application))
{
return;
}
2025-08-24 13:49:55 +08:00
this.application = application;
}
/// <summary>
/// 【核心功能】关闭当前应用程序。
/// </summary>
public void Shutdown() => application?.Shutdown();
/// <summary>
/// 根据提供的资源键尝试从当前主题管理器的资源字典中查找资源。
/// </summary>
/// <param name="resourceKey">要查找的资源的键。</param>
/// <returns>如果找到则返回与指定键关联的对象否则返回null。</returns>
public object? TryFindResource(object resourceKey) => Resources[resourceKey];
/// <summary>
/// 获取当前应用程序的ThemeManager实例。此属性确保在整个应用程序生命周期中只有一个ThemeManager实例。
/// </summary>
/// <remarks>
/// 该属性通过检查是否存在已创建的ThemeManager实例来工作。如果尚未创建实例它将使用当前的应用程序上下文创建一个新的实例。这样可以保证在任何需要访问ThemeManager的地方都能得到相同的实例从而支持单例模式。
/// </remarks>
public static ThemeManager Current
{
get
{
_themeManagerInstance ??= new ThemeManager(Application.Current);
2025-08-24 13:49:55 +08:00
return _themeManagerInstance;
}
}
/// <summary>
/// 获取或设置应用程序的主窗口。该属性允许访问和修改当前应用程序实例中的主窗口。
/// </summary>
/// <remarks>
/// 通过此属性可以获取当前应用程序的主窗口对象或者设置一个新的主窗口对象。如果应用程序实例不为空则直接使用其MainWindow属性否则使用内部存储的mainWindow变量。当设置新的主窗口时如果应用程序实例存在则同时更新应用程序实例的MainWindow属性。
/// </remarks>
public Window MainWindow
{
get => application?.MainWindow ?? mainWindow!;
set { if (application != null) application.MainWindow = value; mainWindow = value; }
}
/// <summary>
/// 获取或设置当前应用程序的资源字典。该属性用于管理和访问应用程序级别的资源,如样式、模板和控件资源。
/// </summary>
/// <remarks>
/// 通过`Resources`属性可以访问和修改应用程序的全局资源字典。这对于统一管理应用的主题、样式以及其他UI相关的资源非常有用。如果还没有为应用程序初始化资源字典则在首次访问时会自动创建一个新的`ResourceDictionary`实例,并尝试加载默认主题和其他相关资源到这个字典中。此外,还允许直接替换整个资源字典,以实现动态改变应用程序外观的需求。
/// </remarks>
public ResourceDictionary Resources
{
get
{
2025-08-26 21:33:20 +08:00
if (resources == null)
2025-08-24 13:49:55 +08:00
{
resources = [];
2025-08-26 21:33:20 +08:00
try
{
var themesDictionary = new ThemesDictionary() { Mode = ActiveThemeMode, Palette = ActiveThemePalette };
var controlsDictionary = new ControlsDictionary();
resources.MergedDictionaries.Add(themesDictionary);
resources.MergedDictionaries.Add(controlsDictionary);
}
catch { /* 忽略初始化异常 */ }
2025-08-24 13:49:55 +08:00
}
2025-08-26 21:33:20 +08:00
2025-08-24 13:49:55 +08:00
return application?.Resources ?? resources;
}
set
{
if (application != null) application.Resources = value;
resources = value;
}
}
/// <summary>
///
/// </summary>
public static ThemeMode ActiveThemeMode { get; private set; } = GetAppThemeMode();
/// <summary>
///
/// </summary>
public static ThemePalette ActiveThemePalette { get; private set; } = GetAppThemePalette();
2025-08-24 13:49:55 +08:00
#endregion
}
}