5

我正在运行一个测试单元(并了解它们)。很简单,我的单元创建一个列表并将其传递给我的 MainWindow。

我遇到的问题是在show()主窗口结束后单元方法结束。我希望在关闭 MainWindow 之前该单元不会完成。这就是我所做的(见下文) - 它显然不起作用并且感觉我在这里走错了路。我怎样才能正确地做到这一点?

    [TestClass]
    public class Logging
    {
        bool continueOn = true;
        [TestMethod]
        public void ShowLogs()
        {
            ShowResults(createLogList());
        }

        private void ShowResults(List<Log> logList)
        {
            MainWindow mw = new MainWindow(logList);
            mw.Closed += mw_Closed;  
            mw.Show();

            while (continueOn)
            { }
        }

        void mw_Closed(object sender, EventArgs e)
        {
            this.continueOn = false;
        }

        private List<Log> createLogList()
        {
            List<Log> listLog = new List<Log>();
            //logic 
            return listLog;            
        }

也许我必须把它放到后台工作线程上并监控它 - 老实说我不知道​​,在我浪费时间之前,我会很感激一些指导。

4

2 回答 2

15

必须在支持 WPF 窗口基础结构(消息泵送)的线程上创建并显示 WPF 窗口。

[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();
    }

注意:

  • 必须在新线程中创建并显示窗口。
  • 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.

于 2012-11-14T16:18:17.363 回答
2

Of course, since it is only for testing, using

ShowDialog() 

may be an option instead of 'Show()'

于 2014-03-24T15:00:14.057 回答