我嘗試在我的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/
謝謝,System.Windows.Threading.Dispatcher.Run();有助於保持窗戶的開放。 我正在使用線程,因爲代碼拋出InvalidOperationException「調用線程必須是STA,因爲許多UI組件都需要這個。」 – David 2012-04-24 09:35:19
你的Main方法中的[STAThread]屬性將處理該異常,並且不需要使用另一個線程並調用'System.Windows.Threading.Dispatcher.Run();' – Tsabo 2012-04-24 09:39:35