简体   繁体   中英

reuse code for RelayCommand

I'm using MVVM light for a WPF application. I have a view model with several commands that use the RelayCommand. Since the code is very similar for each command, I created a GetCommand Method. But the resulting RelayCommand does not work if I use the param inside the RelayCommand. If I don't use the param everything works fine (except that I can't pass a value).

Can someone explain why this happens and what other solution there is to reuse the code without copy & paste?

Below is a very reduced version of my code that shows only the important parts:

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

This is how I usually use RelayCommands where I just bind the commands to methods.

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

You may be looking for something like the following

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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