C# 重新启动WPF应用程序将更改主窗口线程所有者
我有一个非常密集的线程应用程序,工作非常好。。。但是,当单击重新启动按钮时。。。它遵循代码,处理viewmodels并关闭主窗口。。。从而返回dialogresult并返回到app.xaml.cs 这就是我实现重启的方式C# 重新启动WPF应用程序将更改主窗口线程所有者,c#,wpf,C#,Wpf,我有一个非常密集的线程应用程序,工作非常好。。。但是,当单击重新启动按钮时。。。它遵循代码,处理viewmodels并关闭主窗口。。。从而返回dialogresult并返回到app.xaml.cs 这就是我实现重启的方式 base.OnStartup(e); // Register required assemblies. RegisterAssemblies(); foreach (FolderType type in FolderType.
base.OnStartup(e);
// Register required assemblies.
RegisterAssemblies();
foreach (FolderType type in FolderType.GetValues())
{
if (!Directory.Exists(type.Value))
{
Directory.CreateDirectory(type.Value);
}
}
bool? restart = true;
ShutdownMode = System.Windows.ShutdownMode.OnExplicitShutdown;
dynamic window;
MainWindowViewModel viewModel;
while (restart == true)
{
running = true;
string[] files = Directory.GetFiles(FolderType.LASTCONFIGURATION.Value);
lastConfiguration = string.Empty;
if (files.Length != 0)
{
lastConfiguration = files[0];
}
#if (!DEBUG)
if (SystemParameters.PrimaryScreenHeight == 1080)
{
window = new MainWindowHD();
}
else
{
window = new MainWindow();
}
Mouse.OverrideCursor = Cursors.None;
#else
window = new MainWindow();
#endif
window.ShowInTaskbar = false;
viewModel = new MainWindowViewModel(lastConfiguration, "saved_settings.xml", FolderType.CASES + "\\" + "case_configuration.xml");
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
window.DataContext = viewModel;
}
));
restart = window.ShowDialog();
}
if (systemShutdown)
{
Process.Start("shutdown", "/s /t 0");
}
Shutdown(0);
这将再次循环并重置window对象和viewmodel对象,但现在所有其他类中的Application.Current.MainWindow都抱怨拥有它的线程不同。我想我可以通过放置((App)Application.Dispatcher.Invoke来解决这个问题,但是我不希望这样做,因为在重新启动之前没有必要这样做
什么可以解释Application.Current.MainWindow与创建它的线程不同
干杯。只有在应用程序中创建第一个
窗口时才会设置主窗口
属性。重新创建窗口时,需要手动更新MainWindow
属性
此外,如果您的代码运行在对应用程序
的启动
方法的重写中,则不需要使用应用程序.Current
this.MainWindow = window = new MainWindow();
window.ShowInTaskbar = false;
viewModel = new MainWindowViewModel(...);
Dispatcher.BeginInvoke(new Action(() => window.DataContext = viewModel));
restart = window.ShowDialog();
还有一条评论:别忘了高清屏幕的分辨率可能大于1080p。您应该更新您的支票以说明:
if (SystemParameters.PrimaryScreenHeight >= 1080)
刚刚检查了Application.Current.Dispatcher.Invoke和Application.Current.MainWindow.Dispatcher.Invoke,但MainWindow似乎位于一个完全不同的线程上!this.MainWindow=window=new MainWindow()无法修复此问题。。。事实上,我今天早上试着用Application.Current.MainWindow=MainWindow设置它,但也没用。在错误发生之前调试时。。。我可以查看一些MainWindow属性,但Style等其他属性表示需要继续执行以重新评估。