69 lines
2.1 KiB
C#
69 lines
2.1 KiB
C#
using System.Windows;
|
|
using System.Windows.Interop;
|
|
|
|
namespace Sai.Toolkit.Core.Helpers;
|
|
|
|
public sealed record SingletonViewHelper<T>
|
|
where T : Window, new()
|
|
{
|
|
private static T instance;
|
|
private static readonly object Padlock = new();
|
|
|
|
private SingletonViewHelper() { }
|
|
|
|
public static T GetInstance(out bool isNewCreate)
|
|
{
|
|
isNewCreate = false;
|
|
//double-check locking
|
|
if (instance == null)
|
|
{
|
|
isNewCreate = true;
|
|
lock (Padlock)
|
|
{
|
|
instance ??= new T();
|
|
instance.Closed += OnWindowClosed;
|
|
}
|
|
}
|
|
return instance;
|
|
}
|
|
|
|
private static void OnWindowClosed(object sender, EventArgs e)
|
|
{
|
|
instance = null;
|
|
}
|
|
}
|
|
|
|
public static class SingletonChildWindowManager
|
|
{
|
|
private static readonly Dictionary<Type, Window> Windows = [];
|
|
public static void ShowOrActivate<TWindow, TViewModel>(params object[] viewModelParams)
|
|
where TWindow : Window, new()
|
|
where TViewModel : class
|
|
{
|
|
var windowType = typeof(TWindow);
|
|
if (Windows.TryGetValue(windowType, out var window) && window != null)
|
|
{
|
|
window.Activate();
|
|
}
|
|
else
|
|
{
|
|
//CloseAllWindowsExcept(windowType);
|
|
Windows[windowType] = new TWindow();
|
|
Windows[windowType].Closed += (sender, args) => Windows[windowType] = null;
|
|
if (Windows[windowType].DataContext == null || Windows[windowType].DataContext is not TViewModel)
|
|
{
|
|
if (viewModelParams.Length == 0)
|
|
{
|
|
Windows[windowType].DataContext = Activator.CreateInstance(typeof(TViewModel));
|
|
}
|
|
else
|
|
{
|
|
Windows[windowType].DataContext = Activator.CreateInstance(typeof(TViewModel), viewModelParams);
|
|
}
|
|
}
|
|
_ = new WindowInteropHelper(Windows[windowType]) { Owner = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle };
|
|
Windows[windowType].Show();
|
|
}
|
|
}
|
|
}
|