简体   繁体   English

如何在viewmodel(MVVM Model)wpf应用程序中使用命令行参数

[英]how to use Command line parameter in viewmodel (MVVM Model) wpf application

I have an WPF application which can take command line parameter. 我有一个WPF应用程序,可以采取命令行参数。 I want to use this command line parameter in ViewModel, I have following options to do that. 我想在ViewModel中使用此命令行参数,我有以下选项来执行此操作。

1) create public static variable in app.xaml.cs . 1)在app.xaml.cs中创建公共静态变量。 read command line parameter value in main method and assign it to public static variable. 读取main方法中的命令行参数值并将其分配给公共静态变量。 that can be accessed in viewmodel using App.variablename. 可以使用App.variablename在viewmodel中访问。

2) create environment variable like System.Environment.SetEnvironmentVariable("CmdLineParam", "u") and later use it in viewmodel with Environment.GetEnvironmentVariable("CmdLineParam"). 2)创建环境变量,如System.Environment.SetEnvironmentVariable(“CmdLineParam”,“u”),然后在带有Environment.GetEnvironmentVariable(“CmdLineParam”)的viewmodel中使用它。

I want to ask which approach is good considering MVVM pattern and if there is better method to achieve this. 我想问一下考虑MVVM模式哪种方法很好,以及是否有更好的方法来实现这一点。

I do not think that this issue is related to MVVM at all. 我认为这个问题与MVVM根本没有关系。 A good way to make the command line arguments available to a view model might be to (constructor) inject a service. 使命令行参数可用于视图模型的好方法可能是(构造函数)注入服务。 Let's call it IEnvironmentService : 我们称之为IEnvironmentService

public interface IEnvironmentService
{
  IEnumerable<string> GetCommandLineArguments();
}

The implementation would then use Environment.GetCommandLineArgs (which returns a string array containing the command-line arguments for the current process): 然后,实现将使用Environment.GetCommandLineArgs (它返回包含当前进程的命令行参数的字符串数组):

public class MyProductionEnvironmentService : IEnvironmentService
{
  public IEnumerable<string> GetCommandLineArguments()
  {
    return Environment.GetCommandLineArgs();
  }
}

Your view model would then look like this: 您的视图模型将如下所示:

public class MyViewModel
{
  public MyViewModel(IEnvironmentService service)
  {
    // do something useful here
  }
}

All you have to do now is create and insert the production environment service at run-time (passing it yourself, having it created by IoC container etc.). 您现在要做的就是在运行时创建并插入生产环境服务(自己传递,由IoC容器等创建)。 And use a fake/mock one for unit testing. 并使用假/模拟单元进行单元测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM