【问题标题】:WPF/C# - Window closes when it opensWPF/C# - 窗口打开时关闭
【发布时间】:2012-04-24 09:23:00
【问题描述】:

我尝试在我的 c# 测试应用程序中打开一个 wpf 窗口。 但是当我打开窗口时,它又立即关闭了。

我的代码有什么问题?

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/

【问题讨论】:

    标签: c# wpf window


    【解决方案1】:

    您的代码正在做一些没有明显原因的奇怪事情:

    • 为什么要创建一个新线程,然后将已有的线程放入无限循环中?
    • 为什么要在你的Window 上调用.ToString(),它还属于另一个线程? (我不确定这是否会像大多数其他操作一样导致您的程序由于所有权问题而崩溃,但很有可能)。

    此外,您不会在任何地方创建消息循环,因此即使程序运行,它也会完全不响应用户输入。创建Window 后,无论您在哪个线程中执行此操作,都应该调用

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

    【讨论】:

    • 谢谢,System.Windows.Threading.Dispatcher.Run();有助于保持窗户打开。我正在使用线程,因为代码会抛出 InvalidOperationException “调用线程必须是 STA,因为许多 UI 组件都需要这个。”
    • Main 方法上的 [STAThread] 属性将处理该异常,无需使用另一个线程并调用 System.Windows.Threading.Dispatcher.Run();
    【解决方案2】:

    我相信您的Main() 上缺少 [STAThread] 属性

    【讨论】:

      【解决方案3】:

      您是否尝试使用ShowDialog() 而不是Show()?

      【讨论】:

      • 你为什么认为这很有帮助??!!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-30
      • 2013-12-30
      • 1970-01-01
      • 1970-01-01
      • 2016-06-11
      • 2018-11-26
      相关资源
      最近更新 更多