Files
SzmediTools/Szmedi.Test/SingletonWindowManager.cs
2025-09-16 16:06:41 +08:00

42 lines
1.4 KiB
C#

using System;
using System.Windows;
using System.Windows.Interop;
namespace Szmedi.Test
{
public static class SingletonWindowManager
{
private static Window _currentWindow;
public static void ShowOrActivate<TWindow, TViewModel>(params object[] viewModelParameters)
where TWindow : Window, new()
where TViewModel : class
{
if (_currentWindow == null || _currentWindow is not TWindow)
{
_currentWindow?.Close();
_currentWindow = new TWindow();
if (_currentWindow.DataContext == null || _currentWindow.DataContext is not TViewModel)
{
if (viewModelParameters.Length == 0)
{
_currentWindow.DataContext = Activator.CreateInstance(typeof(TViewModel));
}
else
{
_currentWindow.DataContext = Activator.CreateInstance(typeof(TViewModel), viewModelParameters);
}
}
_currentWindow.Closed += (sender, args) => _currentWindow = null;
_ = new WindowInteropHelper(_currentWindow) { Owner = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle };
_currentWindow.Show();
}
else
{
_currentWindow.Activate();
}
}
}
}