从控制台应用程序显示Wpf窗口 [英] Show Wpf Window from Console App

查看:63
本文介绍了从控制台应用程序显示Wpf窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很简单,尝试从控制台应用程序显示WPF窗口.在我的解决方案中,我得到了一个控制台应用程序,它是启动项目,并创建了一个Wpf窗口,如下所示:

I'm simple trying to show a WPF Window from a Console App. In my solution I got a console application which is the startup project and creates a Wpf Window like this:

class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        var thread = new Thread(Foo);
        thread.Start();

        Console.ReadKey();
    }

    private static void Foo()
    {
        var markerService = new MarkerService();
        var viewModel = new MainViewModel();
        markerService.Register(viewModel);
        var mainView = new MainWindow { DataContext = viewModel };
        mainView.Show();
    }
}

MainWindow MainViewModel 只是空的.当我启动项目时,将显示Wpf窗口,但没有响应(光标忙).

MainWindow and MainViewModel are just empty. When I start the project The Wpf Window is shown but doesn't respond (cursor is busy).

感谢您的帮助.

致谢

推荐答案

您需要使用 Dispatcher.Run 启动消息循环.

You need to use Dispatcher.Run to start a message loop.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using WpfApplication1;
using System.Windows.Threading;

namespace ConsoleApplication2
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            var thread = new Thread(Foo);
            thread.ApartmentState = ApartmentState.STA;
            thread.Start();

            Console.ReadKey();
        }

        private static void Foo()
        {
            var markerService = new MarkerService();
            var viewModel = new MainViewModel();
            markerService.Register(viewModel);
            var mainView = new MainWindow { DataContext = viewModel };
            mainView.Show();

            Dispatcher.Run();
        }
    }
}

或者您可以使用@ mm8建议的应用程序"对象样式,或者第三种方法是:

or you can use the "Application" object style suggested by @mm8, or a 3rd alternative is to just do:

        mainView.ShowDialog(); // internal message pump used

更多信息在这里:

这篇关于从控制台应用程序显示Wpf窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆