Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

c# - Show WPF window from test unit

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() the main window the unit method ends. I want the unit to not finish until I close the MainWindow. This is what I've done (see below) - it obviously doesn't work and feels like I'm on the wrong path here. How can I do this properly?

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

Maybe I have to put this onto a background worker thread and monitor that - to be honest I've no idea and before I waste hours, I'd appreciate some guidance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...