重新启动WPF应用程序更改Mainwindow线程所有者

时间:2013-03-27 18:46:21

标签: c# wpf

我有一个非常强大的线程应用程序,效果很好......但是当点击一个重启按钮时...它会跟随代码,处理视图模型并关闭主窗口...因此返回dialogresult并返回到app.xaml.cs。

这就是我实施重启的方式......

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);

这会再次循环并重置窗口对象和viewmodel对象,但现在我所有其他类中的Application.Current.MainWindow都抱怨拥有它的不同线程。我认为通过放置((应用程序)应用程序).​​Dispatcher.Invoke,我不喜欢这样做,因为在重新启动之前没有必要。

什么可以解释Application.Current.MainWindow不是与它创建的同一个线程?

干杯。

1 个答案:

答案 0 :(得分:0)

MainWindow属性仅在应用程序中创建第一个Window时设置。重新创建窗口时,您需要手动更新MainWindow属性。

此外,如果您的代码在覆盖Application.Current的{​​{1}}方法时运行,则不需要使用OnStartup

Application

另一个评论:不要忘记高清屏幕的分辨率可能高于1080p。您应该将支票更新为帐户:

this.MainWindow = window = new MainWindow();
window.ShowInTaskbar = false;
viewModel = new MainWindowViewModel(...);
Dispatcher.BeginInvoke(new Action(() => window.DataContext = viewModel));
restart = window.ShowDialog();
相关问题