107 lines
2.8 KiB
C#
107 lines
2.8 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using System.Windows;
|
|
|
|
using WPFDark.Properties;
|
|
|
|
namespace WPFDark;
|
|
public class ThemeManager
|
|
{
|
|
private static ThemeManager? _themeManagerInstance;
|
|
|
|
private readonly Application? application;
|
|
|
|
//private Window? mainWindow;
|
|
|
|
private ResourceDictionary? resources;
|
|
|
|
internal static string LibraryNamespace => Assembly.GetExecutingAssembly().GetName().Name;
|
|
|
|
public static string ThemesDictionary => $"pack://application:,,,/{LibraryNamespace};component/Themes/Generic.xaml";
|
|
/// <summary>
|
|
/// 获取或设置应用程序的资源。
|
|
/// </summary>
|
|
public object TryFindResource(object resourceKey) { return Resources[resourceKey]; }
|
|
/// <summary>
|
|
/// 初始化 <see cref="ThemeManager"/> 实例.
|
|
/// </summary>
|
|
private ThemeManager(Application? application)
|
|
{
|
|
if (application is null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (!ApplicationHasResources(application))
|
|
{
|
|
return;
|
|
}
|
|
|
|
this.application = application;
|
|
|
|
System.Diagnostics.Debug
|
|
.WriteLine($"INFO | {typeof(ThemeManager)} application is {this.application}", "WPFDark");
|
|
}
|
|
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>
|
|
/// 获取当前UI应用程序。
|
|
/// </summary>
|
|
public static ThemeManager Current
|
|
{
|
|
get
|
|
{
|
|
_themeManagerInstance ??= new ThemeManager(Application.Current);
|
|
|
|
return _themeManagerInstance;
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// 获取或设置应用程序的资源。
|
|
/// </summary>
|
|
public ResourceDictionary Resources
|
|
{
|
|
get
|
|
{
|
|
if (resources is null)
|
|
{
|
|
resources = [];
|
|
|
|
try
|
|
{
|
|
var themesDictionary = new ThemesDictionary();
|
|
var controlsDictionary = new ControlsDictionary();
|
|
resources.MergedDictionaries.Add(themesDictionary);
|
|
resources.MergedDictionaries.Add(controlsDictionary);
|
|
}
|
|
catch
|
|
{
|
|
}
|
|
}
|
|
|
|
return application?.Resources ?? resources;
|
|
}
|
|
set
|
|
{
|
|
if (application is not null)
|
|
{
|
|
application.Resources = value;
|
|
}
|
|
|
|
resources = value;
|
|
}
|
|
}
|
|
}
|