如何基于参数
问题描述:
开始WPF我目前正在开发的是做一些文件操作的应用程序,我希望能够通过控制台或通过UI做操纵(我选择了WPF)。如何基于参数
我非常想说:(伪)
if (Environment.GetCommandLineArgs().Length > 0)
{
//Do not Open WPF UI, Instead do manipulate based
//on the arguments passed in
}
else
{
//Open the WPF UI
}
我读过有关程序启动WPF窗口/应用等几种不同的方式:
Application app = new Application();
app.Run(new Window1());
但我我不完全确定我想将它插入控制台应用程序。
有没有人对我怎样才能做到这一点的最佳做法或建议?主要的处理功能在我创建的Helper类中。所以基本上我不是一个静态的启动方法(如标准控制台应用程序创建),或取决于。
答
通过在应用类有一个事件“启动”,你可以用它的参数的用户界面来访问辅助类。它为您提供通过命令提示符提供的参数。下面是MSDN一个例子:
的App.xaml
<Application x:Class="WpfApplication99.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Startup="App_Startup">
App.xaml.cs
我希望这将有助于。
答
有2个选项可以获得命令行参数
1)如果你想读取参数OnStartup
。这对args
的全球访问非常有用。
覆盖OnStartup
在App.xaml.cs
并查看StartupEventArgs
类的Args
属性。
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
foreach (string arg in e.Args)
{
// TODO: whatever
}
base.OnStartup(e);
}
}
2)另一种简单的方法是从环境对象中读取参数。
Environment.GetCommandLineArgs();
这可以从应用程序的任何地方使用,如从Form/Page也可以。
这是正确的做法。请参阅http://msdn.microsoft.com/en-us/library/system.windows.application.startup.aspx – Eugene 2012-08-02 02:41:33
除了上面的建议,我相信值得注意的是,您需要删除StartupUri属性App.xaml(如果存在)。如果你不这样做,你会产生两个窗口实例。 – Tada 2012-08-02 03:03:02