将命令行参数传递到WPF C#应用程序并访问其值
本文关键字:访问 应用程序 命令行 参数传递 WPF | 更新日期: 2023-09-27 18:20:40
因此,从这篇文章中,我获得了以下代码,用于将命令行参数传递到我的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);
}
}
}
然后应用程序启动我的MainWindow.xaml,应用程序运行,但在MainWindow.xam的viewModel(MainViewModel.cs)中,我想访问App.CustomerCode.的值
这是处理命令行参数的正确方法吗?是否可以访问CustomerCode的值?
访问客户代码的一种简单方法是用new
关键字覆盖Application.Current
属性(正如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);
}
}
在视图模型中,您可以通过编写App.Current.CustomerCode
来访问客户代码。
然而,如果你想要一种关于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();
}
若要实现此操作,必须删除App.xaml
中的StartupUri
条目,否则手动创建的主窗口将不会显示。
您的视图模型如下所示:
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
}
这种方法比访问静态App.Current
属性更灵活,因为视图模型独立于App
类(即它没有对它的引用)。
如果你想了解更多关于依赖注入的信息,只需谷歌一下,你就会发现很多例子。如果你想深入了解更多内容,我还可以推荐Mark Seemann的优秀著作《.NET中的依赖注入》。
我不知道你的真正意图,但下面的代码应该会对你有所帮助。
您可以通过在项目调试设置中添加一些参数来尝试此操作。
如果您的参数包含空格,您应该使用"符号来区分它们。但在某些情况下,您可以使用应用程序配置文件来代替此操作。您可以从"项目设置"添加一些设置,也可以直接通过Settings.Settings文件进行编辑。
如果你需要/喜欢启动参数,就在这里。
//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();
}
}