using System.Windows; using System.Windows.Interop; namespace Sai.Toolkit.Core.Helpers; public sealed record SingletonViewHelper 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 Windows = []; public static void ShowOrActivate(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(); } } }