我使用波纹管代码在单独的线程中显示WPF窗口,这是工作查找但是我有很多窗口所以这个代码有点重复。有人可以建议如何通过传递Windows等通用它? THX
// Create a thread
Thread newWindowThread = new Thread(new ThreadStart( () =>
{
SynchronizationContext.SetSynchronizationContext(
new DispatcherSynchronizationContext(
Dispatcher.CurrentDispatcher));
Window1 tempWindow = new Window1();
tempWindow.Closed += (s,e) => Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Background);
tempWindow.Show();
System.Windows.Threading.Dispatcher.Run();
}));
newWindowThread.SetApartmentState(ApartmentState.STA);
newWindowThread.IsBackground = true;
newWindowThread.Start();
答案 0 :(得分:1)
所以可能的重构可能是:
public static class WindowHelper
{
public static void CreateWindow<TWindow>(Action onClose = null)
where TWindow : Window, new()
{
// Create a thread
Thread newWindowThread = new Thread(new ThreadStart(() =>
{
SynchronizationContext.SetSynchronizationContext(
new DispatcherSynchronizationContext(
Dispatcher.CurrentDispatcher));
TWindow tempWindow = new TWindow();
tempWindow.Closed += (s, e) =>
{
if(onClose != null)
onClose();
Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Backgroud);
};
tempWindow.Show();
System.Windows.Threading.Dispatcher.Run();
}));
newWindowThread.SetApartmentState(ApartmentState.STA);
newWindowThread.IsBackground = true;
newWindowThread.Start();
}
}
您可以将此方法称为:
WindowHelper.CreateWindow<Window1>();
或
WindowHelper.CreateWindow<Window1>(() => Console.WriteLine("Closed"));