Search code examples
c#wpfmvvmicommandrelaycommand

C# ICommand / RelayCommand


I recently started learning WPF (with MVVM pattern). I have got a question about ICommand implementation...

private ICommand _confirmOptionCommand;

public ICommand ConfirmOptionCommand
{
   get
   {
      if (_confirmOptionCommand == null)
      {
        _confirmOptionCommand = new RelayCommand(ConfirmOptionMethod);
      }
      return _confirmOptionCommand;
   }
}

private void ConfirmOptionMethod() { ... }

But I can write like this:

private RelayCommand _confirmOptionCommand;

public RelayCommand ConfirmOptionCommand { ... }

private void ConfirmOptionMethod() { ... }

What advantages ICommand has got? Or what is the difference between them?


Solution

  • RelayCommand is an ICommand, just a different implementation which allows you to call a delegate when the command is executed.

    When you write ICommand instead of RelayCommand as the variable type, you still have to point to an ICommand object. But you only have access to the ICommand interface. If you want other aspects which the object have, you need the derived class reference. In our case, it's a RelayCommand reference..

    Here's how a RelayCommand may look like (Not gonna compile, but you get it):

    public class RelayCommand<T> : ICommand {
        private Action<T> action;
    
        public RelayCommand(T action){
            this.action = action;
        }
    
        public bool CanExecute(obj param){
            return true;
        }
    
        public void Execute(obj param){
            this.action((T)param);
        }
    
        public CanExecuteEventHandler CanExecuteChanged;
    
    }
    

    There are other types of ICommand such as RoutedUICommand which works with event handlers.