将命令行参数传递到 WPF C# 应用程序并访问其值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25660973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:27:37  来源:igfitidea点击:

Passing command line arguments into WPF C# application and accessing its value

c#wpfcommand-line-arguments

提问by user1

So from this postI got the following code for passing command line arguments into my WPF Application

所以从这篇文章中,我得到了以下代码,用于将命令行参数传递到我的 WPF 应用程序中

public partial class App : Application
{
    private string _customerCode;
    public string CustomerCode
    {
        get { return _customerCode; }
        set { _customerCode = value; }
    }


    protected override void OnStartup(StartupEventArgs e)
    {
        if (e.Args.Count() != 0)
        {
            CustomerCode = e.Args[0].Replace("/", string.Empty); 
        }
    }
}

The application then starts my MainWindow.xaml and the application runs but in the viewModel for MainWindow.xaml (MainViewModel.cs) I would like to access the value of App.CustomerCode.

然后应用程序启动我的 MainWindow.xaml 并运行应用程序,但在 MainWindow.xaml (MainViewModel.cs) 的视图模型中,我想访问 App.CustomerCode 的值。

Is this the right way to deal with command line arguments and is it possible to access the value of CustomerCode?

这是处理命令行参数的正确方法吗?是否可以访问 CustomerCode 的值?

回答by feO2x

One of the easy ways to access the customer code is to overwrite the Application.Currentproperty with the newkeyword (as more or less Davut has pointed out in his answer):

访问客户代码的一种简单方法是Application.Currentnew关键字覆盖该属性(正如 Davut 在他的回答中或多或少指出的那样):

public class App : Application
{
    public static new App Current
    {
        get { return (App) Application.Current; }
    }

    public string CustomerCode { get; set; }
    protected override void OnStartup(StartupEventArgs e)
    {
        this.CustomerCode = e.Args[0].Replace("/", string.Empty);
        base.OnStartup(e);
    }
}

In your view model you can then access the customer code by writing App.Current.CustomerCode.

在您的视图模型中,您可以通过编写App.Current.CustomerCode.

However, if you want a more object-oriented way regarding the SOLID principles, I would advise to do the following: in your OnStartupmethod, create the view model and the main window in code and show it. Using this approach, you can inject the customer code to the view model, e.g. via constructor injection. The OnStartupmethod would look like this:

但是,如果您想要一种关于 SOLID 原则的更面向对象的方式,我建议您执行以下操作:在您的OnStartup方法中,在代码中创建视图模型和主窗口并显示它。使用这种方法,您可以将客户代码注入视图模型,例如通过构造函数注入。该OnStartup方法如下所示:

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

    // Composition root
    var customerCode = e.Args[0].Replace("/", string.Empty);

    // Here I inject the customer code to the view model so that 
    // it can save it in a field and use it later.
    // This is called dependency injection (here it's constructor injection)
    var mainWindowViewModel = new MainWindowViewModel(customerCode);
    MainWindow = new MainWindow { DataContext = mainWindowViewModel };
    MainWindow.Show();
}

For this to work, you have to remove the StartupUrientry in App.xaml- otherwise your manually created main window will not show up.

为此,您必须删除StartupUri条目App.xaml- 否则您手动创建的主窗口将不会显示。

Your view model would look like this:

您的视图模型如下所示:

public class MainWindowViewModel
{
    private readonly string _customerCode;

    public MainWindowViewModel(string customerCode)
    {
        if (customerCode == null)
            throw new ArgumentNullException("customerCode");

        _customerCode = customerCode;
    }

    // Other code in this class can access the _customerCode field
    // to retrieve the value from the command line
}

This approach is a more flexible than to access the static App.Currentproperty as your view model is independent of the Appclass (i.e. it has no references to it).

这种方法比访问静态App.Current属性更灵活,因为您的视图模型独立于App类(即它没有对它的引用)。

If you want to learn more about dependency injection, just google it, you'll find plenty of example. I can also recommend the excellent book Dependency Injection in .NETby Mark Seemann, if you want to dive in more.

如果你想了解更多关于依赖注入的知识,只要谷歌一下,你会找到很多例子。如果您想深入了解,我还可以推荐Mark Seemann所著的优秀书籍Dependency Injection in .NET

回答by Davut Gürbüz

I do not know your real intent, but the code below should help you.

我不知道你的真实意图,但下面的代码应该可以帮助你。

You can try this by adding some arguments on project debug settings.

您可以通过在项目调试设置上添加一些参数来尝试此操作。

If your parameters contains blank spaces you should use "" signs to distinguish them. But instead of doing this you can use Application Config file for some cases. You can add some Settings from Project Settings or directly editing by settings.settings file.

如果您的参数包含空格,您应该使用“”符号来区分它们。但是,您可以在某些情况下使用应用程序配置文件,而不是这样做。您可以从项目设置中添加一些设置或直接通过 settings.settings 文件进行编辑。

If you need/fancy startup args, here is it.

如果你需要/花哨的启动参数,这里是它。

//App
public partial class App : Application
{
    public string CustomerCode { get; set; }
    protected override void OnStartup(StartupEventArgs e)
    {

        this.CustomerCode=e.Args[0].ToString();
        base.OnStartup(e);
    }
}


//MainWindow
 public partial class MainWindow : Window
{
    public MainWindow()
    {
        var hereIsMyCode=(Application.Current as App).CustomerCode;
        InitializeComponent();
    }
}