添加项目文件。
This commit is contained in:
68
Sai.Toolkit.Core/Heplers/SingletonViewHelper.cs
Normal file
68
Sai.Toolkit.Core/Heplers/SingletonViewHelper.cs
Normal file
@@ -0,0 +1,68 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user