c# - RelayCommand 的重用代码

标签 c# wpf mvvm mvvm-light relaycommand

我将 MVVM 灯用于 WPF 应用程序。我有一个 View 模型,其中包含几个使用 RelayCommand 的命令。由于每个命令的代码都非常相似,因此我创建了一个 GetCommand 方法。但是,如果我使用 RelayCommand 中的参数,生成的 RelayCommand 将不起作用。如果我不使用参数一切正常(除了我不能传递值)。

有人可以解释为什么会发生这种情况,还有什么其他解决方案可以在不复制和粘贴的情况下重用代码?

下面是我的代码的一个非常简化的版本,它只显示了重要部分:

public class MainViewModel {
   public RelayCommand commandOne = GetCommand("one");
   public RelayCommand commandTwo = GetCommand("two");

   public RelayCommand GetCommand(string param) {
      return new RelayCommand(() => {
         // Do something accessing other properties of MainViewModel
         // to detect if another action is alreay running
         // this code would need to be copy & pasted everywhere
         if(param == "one")
            _dataService.OneMethod();
         else if(param == "two")
            _dataService.TwoMethod();
         else
            _dataService.OtherMethod();
         var name = param;
      });
   }
}

最佳答案

这就是我通常使用 RelayCommands 的方式,我只是将命令绑定(bind)到方法。

public class MainViewModel {
    public MainViewModel()
    {
        CommandOne = new RelayCommand<string>(executeCommandOne);
        CommandTwo = new RelayCommand(executeCommandTwo);
    }

    public RelayCommand<string> CommandOne { get; set; }

    public RelayCommand CommandTwo { get; set; }

    private void executeCommandOne(string param)
    {
        //Reusable code with param
    }

    private void executeCommandTwo()
    {
        //Reusable code without param
    }
}

关于c# - RelayCommand 的重用代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20244455/

相关文章:

c# - "Global"事件处理器

c# - LINQPad:使用 (.NET4) VS2010 程序集时出现 "BadImageFormatException"?

c# - 指定的类型转换无效?

wpf - 使用 PRISM 构建数据库感知应用程序

c# - MVVM、XML 和主/详细方案

wpf - 命名空间 "clr-namespace:Project.ViewModels"中不存在名称 ViewModel

WPF//MahApps.Metro//Caliburn.Micro//Flyout//HeaderedContentControl

c# - Windows Phone 8.1 内存问题

c# - 可查询的混淆

c# - 使用 ClosedXML 和 OpenFileDialog 将 Excel 导入 DataGrid