【问题标题】:how to use Command line parameter in viewmodel (MVVM Model) wpf application如何在视图模型(MVVM 模型)wpf 应用程序中使用命令行参数
【发布时间】:2013-10-12 09:22:41
【问题描述】:

我有一个可以接受命令行参数的 WPF 应用程序。我想在 ViewModel 中使用这个命令行参数,我有以下选项可以做到这一点。

1) 在 app.xaml.cs 中创建公共静态变量。在 main 方法中读取命令行参数值并将其分配给公共静态变量。可以使用 App.variablename 在 vi​​ewmodel 中访问。

2) 创建像 System.Environment.SetEnvironmentVariable("CmdLineParam", "u") 这样的环境变量,然后通过 Environment.GetEnvironmentVariable("CmdLineParam") 在视图模型中使用它。

我想问考虑到 MVVM 模式,哪种方法更好,是否有更好的方法来实现这一点。

【问题讨论】:

    标签: c# wpf mvvm viewmodel command-line-arguments


    【解决方案1】:

    我认为这个问题根本与 MVVM 无关。使命令行参数可用于视图模型的一种好方法可能是(构造函数)注入服务。我们就叫它IEnvironmentService

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

    然后该实现将使用Environment.GetCommandLineArgs(它返回一个字符串数组,其中包含当前进程的命令行参数):

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

    您的视图模型将如下所示:

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

    您现在要做的就是在运行时创建和插入生产环境服务(自己传递它,让 IoC 容器创建它等)。并使用假/模拟的进行单元测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-28
      • 2013-01-31
      • 1970-01-01
      • 2011-12-30
      • 1970-01-01
      相关资源
      最近更新 更多