将命令行参数传递到WPF C#应用程序并访问其值 [英] Passing command line arguments into WPF C# application and accessing its value

查看:104
本文介绍了将命令行参数传递到WPF C#应用程序并访问其值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,从此帖子中,我获得了以下代码来传递命令行参数放入我的WPF应用程序

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

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); 
        }
    }
}

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

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.

这是正确的吗

推荐答案

我不知道您的意图是什么? ,但是下面的代码应该可以为您提供帮助。

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.

如果您的参数包含空格,则应使用符号来区分它们。但是,在某些情况下,您可以使用Application Config文件来代替执行此操作。您可以从项目设置中添加一些设置,也可以直接通过settings.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.

如果您需要/喜欢启动args,就在这里。

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();
    }
}

这篇关于将命令行参数传递到WPF C#应用程序并访问其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆