2013-03-27 32 views
0

我有一個非常強大的線程應用程序,效果很好......但是,當單擊重新啓動按鈕時...它通過代碼進行處理,放置viewmodels並關閉主窗口...因此返回dialogresult並返回到app.xaml.cs.重新啓動WPF應用程序更改主窗口線程所有者

這是怎麼了,我實現重啓...

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

這再次開啓循環和重置窗口對象和視圖模型對象,但現在Application.Current.MainWindow我的所有其他類抱怨擁有它的另一個線程。我想我通過把((應用程序)應用程序).​​Dispatcher.Invoke得到這一點,但我不希望在重新啓動前沒有必要。

什麼能解釋Application.Current.MainWindow不是它創建的同一個線程?

乾杯。

+0

剛纔檢查Application.Current.Dispatcher.Invoke和Application.Current.MainWindow.Dispatcher.Invoke但主窗口似乎是在完成不同的線程! – bl4kh4k 2013-03-27 18:59:35

回答

0

MainWindow屬性僅在應用程序中創建第一個Window時設置。重新創建窗口時,您需要手動更新MainWindow屬性。

此外,如果您的代碼正在運行方法Application的覆蓋範圍內,則不需要使用Application.Current

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

一個其他評論:不要忘了,HD的屏幕可能有一個分辨率比1080更大。您應該更新您的支票考慮到這一點:

if (SystemParameters.PrimaryScreenHeight >= 1080) 
+0

this.MainWindow = window = new MainWindow()沒有解決這個問題......我實際上已經嘗試過通過Application.Current.MainWindow = mainWindow來設置它,但是也沒有工作。在錯誤發生之前進行調試時...我可以查看一些MainWindow屬性,但其他人(如Style)則需要繼續執行才能重新評估。 – bl4kh4k 2013-03-27 20:16:08

相關問題