Files
Shrlalgo.RvKits/Sai.Toolkit.Core/Heplers/SingletonViewHelper.cs
2024-10-08 16:21:39 +08:00

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();
}
}
}