2012-04-24 203 views
2

我嘗試在我的c#測試應用程序中打開一個wpf窗口。 但是當我打開窗戶時,它會立即關閉。WPF/C# - 窗口在打開時關閉

我的代碼有什麼問題?

Main.cs(也可here):

namespace Project1 
{ 
    class TestClass 
    { 
     public static MainWindow _mainWindow = null; 

     static void Main(string[] args) 
     { 
      Thread t = new Thread(new ThreadStart(ThreadProc)); 
      t.SetApartmentState(ApartmentState.STA); 
      t.Start(); 

      while (true) 
      { 
       System.Threading.Thread.Sleep(1000); 
       _mainWindow.ToString(); 
      } 
     } 

     public static void ThreadProc() 
     { 
      TestClass2 testClass = new TestClass2(); 
      testClass.Open(); 
     } 
    } 

    class TestClass2 
    { 
     public void Open() 
     { 
      TestClass._mainWindow = new MainWindow(); 
      TestClass._mainWindow.Show(); 
      Console.WriteLine("=)"); 
     } 
    } 
} 

MainWindow.xaml:

http://paste.ubuntu.com/943800/

回答

7

您的代碼做一些奇怪的事情它沒有明顯的原因:

  • 爲什麼要創建一個新的線程,然後把你已經進入一個無限循環的一個?
  • 爲什麼電話.ToString()在您的Window,另外由另一個線程擁有? (我不確定這會不會像大多數其他操作一樣會因爲所有權問題而導致程序崩潰,但很可能)。

此外,您不會在任何地方創建消息循環,所以即使程序運行,它也完全不響應用戶輸入。創建Window,在你做任何線索之後,你應該叫

System.Windows.Threading.Dispatcher.Run(); 
+0

謝謝,System.Windows.Threading.Dispatcher.Run();有助於保持窗戶的開放。 我正在使用線程,因爲代碼拋出InvalidOperationException「調用線程必須是STA,因爲許多UI組件都需要這個。」 – David 2012-04-24 09:35:19

+1

你的Main方法中的[STAThread]屬性將處理該異常,並且不需要使用另一個線程並調用'System.Windows.Threading.Dispatcher.Run();' – Tsabo 2012-04-24 09:39:35

0

你嘗試使用ShowDialog(),而不是Show()

+0

缺少[STAThread]屬性爲什麼你認爲是有幫助的?? !! – AymenDaoudi 2014-11-25 11:30:55

2

我相信你在你的Main()