Show WPF window from test unit

前端 未结 2 594
谎友^
谎友^ 2020-12-10 08:37

I am running a test unit (and learning about them). Quite simply, my unit creates a List and passes it to my MainWindow.

The issue I have is after I show()

2条回答
  •  有刺的猬
    2020-12-10 09:03

    The WPF Window must be created and shown on a thread which supports the WPF window infrastructure (message pumping).

    [TestMethod]
        public void TestMethod1()
        {
            MainWindow window = null;
    
            // The dispatcher thread
            var t = new Thread(() =>
            {
                window = new MainWindow();
    
                // Initiates the dispatcher thread shutdown when the window closes
                window.Closed += (s, e) => window.Dispatcher.InvokeShutdown();
    
                window.Show();
    
                // Makes the thread support message pumping
                System.Windows.Threading.Dispatcher.Run();
            });
    
            // Configure the thread
            t.SetApartmentState(ApartmentState.STA);
            t.Start();
            t.Join();
        }
    

    Note that:

    • The window must be created and shown inside the new thread.
    • You must initiate a dispatcher (System.Windows.Threading.Dispatcher.Run()) before the ThreadStart returns, otherwise the window will show and die soon after.
    • The thread must be configured to run in STA apartment.

    For more information, visit this link.

提交回复
热议问题