简体   繁体   中英

WPF/C# - Window closes when it opens

I try to open an wpf window in my c# test application. But when I open the window, it is immediately closed again.

Whats wrong in my code?

Main.cs (also available 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/

Your code is doing some strange things for which there is no apparent reason:

  • Why create a new thread and then put the one you already have into an endless loop?
  • Why call .ToString() on your Window , which additionally is owned by a different thread? (I 'm not sure if this would cause your program to crash due to the ownership issue like most other operations would, but it's probable).

Furthermore, you do not create a message loop anywhere so even if the program worked it would be completely unresponsive to user input. After creating your Window , in whatever thread you do it, you should call

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

我相信你在Main()上缺少[STAThread]属性

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM