Files
ShrlAlgoToolkit/WPFluent/UiApplication.cs

134 lines
3.2 KiB
C#
Raw Normal View History

using WPFluent.Appearance;
using WPFluent.Extensions;
using WPFluent.Markup;
namespace WPFluent;
/// <summary>
2025-04-24 20:56:44 +08:00
/// 表示 UI 应用程序。
/// </summary>
public class UiApplication
{
private static UiApplication? _uiApplication;
2025-04-24 20:56:44 +08:00
private readonly Application? application;
private Window? _mainWindow;
private ResourceDictionary? _resources;
/// <summary>
2025-04-24 20:56:44 +08:00
/// 初始化 <see cref="UiApplication"/> 实例.
/// </summary>
public UiApplication(Application application)
{
if (application is null)
{
return;
}
if (!ApplicationHasResources(application))
{
return;
}
2025-04-24 20:56:44 +08:00
this.application = application;
System.Diagnostics.Debug
2025-04-24 20:56:44 +08:00
.WriteLine($"INFO | {typeof(UiApplication)} application is {this.application}", "WPFluent");
}
private static bool ApplicationHasResources(Application application)
{
return application
.Resources.MergedDictionaries
.Where(e => e.Source is not null)
.Any(
e => e.Source
.ToString()
.Contains(ApplicationThemeManager.LibraryNamespace, StringComparison.OrdinalIgnoreCase));
}
/// <summary>
2025-04-24 20:56:44 +08:00
/// 将应用程序的 变为 shutdown 模式。
/// </summary>
2025-04-24 20:56:44 +08:00
public void Shutdown() { application?.Shutdown(); }
/// <summary>
/// Gets or sets the application's main window.
/// </summary>
public object TryFindResource(object resourceKey) { return Resources[resourceKey]; }
/// <summary>
2025-04-24 20:56:44 +08:00
/// 获取当前应用程序。
/// </summary>
public static UiApplication Current
{
get
{
_uiApplication ??= new UiApplication(Application.Current);
return _uiApplication;
}
}
/// <summary>
/// Gets a value indicating whether the application is running outside of the desktop app context.
/// </summary>
2025-04-24 20:56:44 +08:00
public bool IsApplication => application is not null;
/// <summary>
/// Gets or sets the application's main window.
/// </summary>
public Window? MainWindow
{
2025-04-24 20:56:44 +08:00
get => application?.MainWindow ?? _mainWindow;
set
{
2025-04-24 20:56:44 +08:00
if (application != null)
{
2025-04-24 20:56:44 +08:00
application.MainWindow = value;
}
_mainWindow = value;
}
}
/// <summary>
/// Gets or sets the application's resources.
/// </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
{
}
}
2025-04-24 20:56:44 +08:00
return application?.Resources ?? _resources;
}
set
{
2025-04-24 20:56:44 +08:00
if (application is not null)
{
2025-04-24 20:56:44 +08:00
application.Resources = value;
}
_resources = value;
}
}
}