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";
///
/// 获取或设置应用程序的资源。
///
public object TryFindResource(object resourceKey) { return Resources[resourceKey]; }
///
/// 初始化 实例.
///
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 is not null && application
.Resources.MergedDictionaries
.Where(e => e.Source is not null)
.Any(
e => e.Source
.ToString()
.Contains(LibraryNamespace));
}
///
/// 获取当前UI应用程序。
///
public static ThemeManager Current
{
get
{
_themeManagerInstance ??= new ThemeManager(Application.Current);
return _themeManagerInstance;
}
}
///
/// 获取或设置应用程序的资源。
///
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;
}
}
}