我尝试在我的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