Start WPF Application in Console Application

前端 未结 1 403
心在旅途
心在旅途 2020-12-18 12:12

Is it possible to start WPF Application in Console mode?

public partial class App : Application
{
    public App()
    {
        InitializeComponent();
    }         


        
相关标签:
1条回答
  • 2020-12-18 13:08

    You could declare a Window and then start your app this way:

    var application = new System.Windows.Application();
    application.Run(new Window());
    

    EDIT:

    You seem a bit confused, so let me explain:

    Say you have a program:

    using System;
    
    namespace ConsoleApplication
    {
        class Program
        {
            [STAThread]
            static void Main(string[] args)
            {
                RunApplication();
            }
    
            private static void RunApplication()
            {
                var application = new System.Windows.Application();
                application.Run();
            }
        }
    }
    

    This will run a WPF application with no Window.

    If, on the other hand, you pass a Window into application.Run(), you will get a WPF window. App should not derive from Window, since it should derive from Application.

    Application.Run method either takes no arguments or a Window. It does not take Application. Therefore, if you want to start a previously created Application, as you have over there, you should do something like this:

    private static void RunApplication()
    {
        var application = new App();
        application.Run();  // add Window if you want a window.
    }
    

    Lastly, if you want to just use application.Run() and not have to pass a specific Window, just declare a starting Window in your Application XAML using StartupUri:

    <Application x:Class="WPF.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="SomeWindow.xaml">
    </Application>
    
    0 讨论(0)
提交回复
热议问题