Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 42 ยท MVVM and Navigation

Commands and the MVVM Community Toolkit

Handle button taps in MVVM with ICommand, write your own RelayCommand and AsyncRelayCommand, then use CommunityToolkit.Mvvm source generators ObservableProperty and RelayCommand. Includes runnable stand-ins.

In MVVM a button does not call a method on the page; it is bound to a command exposed by the view model. A command is an object that knows how to run an action and whether it may run right now. This lesson explains the ICommand interface, builds the two common implementations by hand so you understand them, and then shows how the CommunityToolkit.Mvvm package writes most of the boilerplate for you.

MAUI controls cannot run on this site, so the XAML is read-only. ICommand is part of .NET itself, so the command classes below are real code that runs on Piston. The CommunityToolkit.Mvvm package is a NuGet package and is not available in our runner, so its source-generator code is read-only and we run the hand-written equivalent instead.

ICommand

C#
public interface ICommand
{
    event EventHandler? CanExecuteChanged;
    bool CanExecute(object? parameter);
    void Execute(object? parameter);
}

A button with a bound command works like this:

  1. When the button appears (and when CanExecuteChanged fires) it calls CanExecute and enables or disables itself.
  2. When the user taps, it calls Execute.
XML
<Button Text="Save" Command="{Binding SaveCommand}" />
<Button Text="Delete" Command="{Binding DeleteCommand}" CommandParameter="{Binding Id}" />

Many controls support Command and CommandParameter: Button, ImageButton, SearchBar, TapGestureRecognizer, MenuItem, ToolbarItem, RefreshView and more. In the view model the command is a property with a getter only.

A hand-written RelayCommand

RelayCommand (also known as DelegateCommand) wraps two delegates, the action and the optional canExecute check:

C#
public class RelayCommand : ICommand
{
    private readonly Action<object?> execute;
    private readonly Func<object?, bool>? canExecute;

    public RelayCommand(Action<object?> execute, Func<object?, bool>? canExecute = null)
    {
        this.execute = execute;
        this.canExecute = canExecute;
    }

    public event EventHandler? CanExecuteChanged;

    public bool CanExecute(object? parameter) => canExecute?.Invoke(parameter) ?? true;
    public void Execute(object? parameter) => execute(parameter);

    public void NotifyCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}

The important part is NotifyCanExecuteChanged: the button does not poll. When the data that decides CanExecute changes (for example the name field becomes non-empty), the view model must raise the event so that the button re-checks.

C# Stand-in: RelayCommand and CanExecute

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Async commands

Most useful actions are asynchronous: a network call, a database write. An async void lambda works but hides exceptions and lets the user tap twice. A proper async command awaits the task, disables itself while running and surfaces errors:

C#
public class AsyncRelayCommand : ICommand
{
    private readonly Func<Task> execute;
    private readonly Func<bool>? canExecute;
    private bool isRunning;

    public AsyncRelayCommand(Func<Task> execute, Func<bool>? canExecute = null)
    {
        this.execute = execute;
        this.canExecute = canExecute;
    }

    public event EventHandler? CanExecuteChanged;

    public bool CanExecute(object? parameter) => !isRunning && (canExecute?.Invoke() ?? true);

    public async void Execute(object? parameter)
    {
        if (!CanExecute(parameter)) return;
        isRunning = true;
        CanExecuteChanged?.Invoke(this, EventArgs.Empty);
        try
        {
            await execute();
        }
        finally
        {
            isRunning = false;
            CanExecuteChanged?.Invoke(this, EventArgs.Empty);
        }
    }
}

Execute must be async void because the interface says void, but all the work happens inside a try/finally so the running flag is always reset. The isRunning check is the "ignore a second tap" guard. The toolkit's AsyncRelayCommand does the same and adds cancellation, an IsRunning property you can bind to an ActivityIndicator, and exception forwarding.

C# Stand-in: AsyncRelayCommand ignores double taps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

CommunityToolkit.Mvvm

The CommunityToolkit.Mvvm NuGet package (also called the MVVM Toolkit) is the standard helper library for MAUI view models. Add it to the project and use source generators: you write a tiny field, the compiler generates the full property and command.

C#
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

public partial class NoteViewModel : ObservableObject
{
    [ObservableProperty]
    [NotifyCanExecuteChangedFor(nameof(SaveCommand))]
    private string text = "";

    [ObservableProperty]
    private bool isBusy;

    public ObservableCollection<string> Notes { get; } = new();

    [RelayCommand(CanExecute = nameof(CanSave))]
    private async Task SaveAsync()
    {
        IsBusy = true;
        try
        {
            await repository.AddAsync(Text);
            Notes.Add(Text);
            Text = "";
        }
        finally
        {
            IsBusy = false;
        }
    }

    private bool CanSave() => !string.IsNullOrWhiteSpace(Text);
}

What the generators do:

  • [ObservableProperty] on the private field text generates a public property Text with SetProperty and change notification, plus OnTextChanged partial methods you can implement. Field names text, _text and m_text all become Text. In newer toolkit versions you can also put the attribute on a partial property.
  • [NotifyPropertyChangedFor(nameof(Greeting))] raises the event of a dependent computed property.
  • [NotifyCanExecuteChangedFor(nameof(SaveCommand))] re-evaluates a command when the property changes.
  • [RelayCommand] on a method generates a command property named after the method without the Async suffix, so SaveAsync gives SaveCommand. For a method returning Task it generates an AsyncRelayCommand with IsRunning.
  • The class must be partial, and it derives from ObservableObject (or ObservableValidator, or ObservableRecipient for messaging).

The view stays identical to the hand-written version:

XML
<Entry Text="{Binding Text}" />
<Button Text="Save" Command="{Binding SaveCommand}" />
<ActivityIndicator IsRunning="{Binding SaveCommand.IsRunning}" />

You can use command parameters with a typed method, [RelayCommand] private void Delete(Product product), and cancellation with [RelayCommand(IncludeCancelCommand = true)] and a CancellationToken parameter, which generates SaveCancelCommand.

Messenger

For communication between view models that do not know each other, the toolkit includes WeakReferenceMessenger: one side calls Send(new ProductAdded(p)), another registers a handler. Use it sparingly; a shared service is often clearer.

Commands versus event handlers

Event handlers (Clicked="OnClicked") are fine for UI-only logic. Commands win when the logic belongs in the view model, when you need CanExecute, or when the action comes from several places (a button, a toolbar item and a swipe). For controls without a Command property, the Community Toolkit's EventToCommandBehavior turns any event into a command call.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does CanExecuteChanged tell a button?

    The button does not poll. It re-evaluates CanExecute only when the command raises CanExecuteChanged.
  2. 2. A SaveAsync method with [RelayCommand] generates which property?

    The generator names the command after the method, removing the Async suffix and adding Command.
  3. 3. Why does an async command guard against a second tap while it runs?

    A user can tap again before the first call finishes, which could duplicate a request or a database insert.
  4. 4. Which class modifier does a view model using [ObservableProperty] need?

    Source generators add the generated members to the other half of a partial class, so the class must be partial.

Summary

  • A command (ICommand) is an action plus a CanExecute check that a control binds to with Command and CommandParameter.
  • Raise CanExecuteChanged when the conditions change; async commands should disable themselves while running.
  • CommunityToolkit.Mvvm's [ObservableProperty] and [RelayCommand] generate properties and commands; classes must be partial.
  • Use event handlers for pure UI work and commands for logic that belongs in the view model.

Next: Dependency Injection and View Models