在控制台应用程序中启动WPF应用程序 [英] Start WPF Application in Console Application
问题描述
是否可以在控制台模式下启动WPF应用程序?
Is it possible to start WPF Application in Console mode?
public partial class App : Application
{
public App()
{
InitializeComponent();
}
}
<Application x:Class="WPF.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
</Application>
[STAThread]
static void Main(string[] args)
{
if (args.Length > 0)
{
switch (args[0].ToLower())
{
case "/g": RunApplication(); break;
}
}
}
private static void RunApplication()
{
var application = new System.Windows.Application();
application.Run(new App());
}
它将显示参数类型"WPF.app"不可分配给参数类型"System.Windows.Window".
It will show Argument type 'WPF.app' is not assignable to parameter type 'System.Windows.Window'.
解决任何可行的解决方案??
Any solution to work around it?? Any different between
1.public局部类App:应用程序
1.public partial class App : Application
2.public局部类App:Window
2.public partial class App : Window
推荐答案
您可以声明一个Window,然后以这种方式启动您的应用程序:
You could declare a Window and then start your app this way:
var application = new System.Windows.Application();
application.Run(new Window());
您似乎有些困惑,所以让我解释一下:
You seem a bit confused, so let me explain:
假设您有一个程序:
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();
}
}
}
这将在没有窗口的情况下运行WPF应用程序.
This will run a WPF application with no Window.
另一方面,如果将Window传递到application.Run(),则将获得WPF窗口.App不应该从Window派生,因为它应该从Application派生.
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方法不带参数或不带窗口.它不需要应用程序.因此,如果要启动以前创建的应用程序,就应该执行以下操作:
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.
}
最后,如果您只想使用 application.Run()
而不需要传递特定的Window,只需使用StartupUri在Application XAML中声明一个启动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>
这篇关于在控制台应用程序中启动WPF应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!