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
350 views
in Technique[技术] by (71.8m points)

c# - Show Wpf Window from Console App

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 and MainViewModel are just empty. When I start the project The Wpf Window is shown but doesn't respond (cursor is busy).

Any help is appreciated.

regards

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

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

More here:


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

...