Search code examples
mvvmxamarinxamarin.formsicommand

Xamarin Forms - Difference Between ICommand and Command?


In Xamarin Forms MVVM projects, I've seen both:

public ICommand MyCommand {...}

and

public Command MyCommand {...}

What is the difference between the two, and when should I use which? Could I replace all ICommand's with Command's with no ill effect?


Solution

  • What is the difference between the two, and when should I use which?

    They both basically provide the same functionality. The first one ICommand allows for more custom implementations of the interface while the second defines an ICommand implementation that wraps a Action. It forces the implementations to have at least a base of Command and also provides a starting point if you don't want to roll your own implementation of ICommand.

    Could I replace all ICommand's with Command's with no ill effect?

    The framework is happy once what you use inherits from ICommand.

    ICommand command = new Command (() => Debug.WriteLine ("Command executed"));
    var button = new Button {
      Text = "Hit me to execute the command",
      Command = command,
    };