简体   繁体   中英

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?

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.

Simplest answer to your Question would be to make it loosely coupled

On saying that, a loosely-coupled class( ICommand ) can be consumed and tested independently of other concrete classes( RelayCommand ).

Consider if you want to change RelayCommand to some other delegating command in future(like DelegateCommand ) to invoke, in this case it will take more time and effort to replace all the consumers were you have used the concrete class reference( RelayCommand ).

On using the ICommand on client while consuming provides a way to switch to any concrete class that implements ICommand without any changes in client(consumers).

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