Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 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 Answer

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...