重用RelayCommand的代码

时间:2013-11-27 13:59:47

标签: c# wpf mvvm mvvm-light relaycommand

我正在将WPVM灯用于WPF应用程序。我有一个视图模型,其中包含几个使用RelayCommand的命令。由于每个命令的代码非常相似,因此我创建了一个GetCommand方法。但是如果我在RelayCommand中使用param,则生成的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;
      });
   }
}

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

您可能正在寻找以下内容

public partial class MainWindow : Window
{
    private RelayCommand myRelayCommand ;
    private string param = "one";

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
    }

    public RelayCommand MyRelayCommand 
    {
        get
        {
            if (myRelayCommand == null)
            {
                myRelayCommand = new RelayCommand((p) => { ServiceSelector(p); });
            }
            return myRelayCommand;
        }
    }

    private void DoSomething()
    {
        MessageBox.Show("Did Something");
    }

    private void ServiceSelector(object p)
    {
        DoSomething();

        if (param == "one")
            MessageBox.Show("one");
        else if (param == "two")
            MessageBox.Show("two");
        else
            MessageBox.Show("else");
        var name = param;
    }
}