|
1 | 1 | # Trigger a Command |
2 | 2 |
|
3 | | -## RelayCommand |
| 3 | +`CommunityToolkit.Mvvm` uses `RelayCommand` to generate a field and property to represents the command for certain method. |
| 4 | + |
| 5 | +## Code Emission |
| 6 | + |
| 7 | +```cs |
| 8 | +[RelayCommand] |
| 9 | +private void RemoveItem(ToDoItemViewModel item) |
| 10 | +{ |
| 11 | + ToDoItems.Remove(item); |
| 12 | +} |
| 13 | +``` |
| 14 | + |
| 15 | +Generated part as following: |
| 16 | + |
| 17 | +- A field of type `RelayCommand`(not the `RelayCommandAttribute`) |
| 18 | +- A property for the generated field typed as `IRelayCommand`. |
| 19 | + |
| 20 | +```cs |
| 21 | +/// <summary>The backing field for <see cref="RemoveItemCommand"/>.</summary> |
| 22 | +[global::System.CodeDom.Compiler.GeneratedCode("CommunityToolkit.Mvvm.SourceGenerators.RelayCommandGenerator", "8.3.0.0")] |
| 23 | +private global::CommunityToolkit.Mvvm.Input.RelayCommand<global::ToDoList.ViewModels.ToDoItemViewModel>? removeItemCommand; // [!code highlight] |
| 24 | +/// <summary>Gets an <see cref="global::CommunityToolkit.Mvvm.Input.IRelayCommand{T}"/> instance wrapping <see cref="RemoveItem"/>.</summary> |
| 25 | +[global::System.CodeDom.Compiler.GeneratedCode("CommunityToolkit.Mvvm.SourceGenerators.RelayCommandGenerator", "8.3.0.0")] |
| 26 | +[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] |
| 27 | +public global::CommunityToolkit.Mvvm.Input.IRelayCommand<global::ToDoList.ViewModels.ToDoItemViewModel> RemoveItemCommand => removeItemCommand ??= new global::CommunityToolkit.Mvvm.Input.RelayCommand<global::ToDoList.ViewModels.ToDoItemViewModel>(new global::System.Action<global::ToDoList.ViewModels.ToDoItemViewModel>(RemoveItem)); // [!code highlight] |
| 28 | +``` |
| 29 | + |
| 30 | +## Behind the `RelayCommand` |
| 31 | + |
| 32 | +To understand how `RelayCommand` works, we should go back to the story of `ICommand` first. |
| 33 | + |
| 34 | +`ICommand` is a builtin interface in .NET, has three parts to describe the command pattern: |
| 35 | +- `Execute`: A real action for the command. |
| 36 | +- `CanExecute`: Telling whether the command can be executed now. |
| 37 | +- `CanExecuteChanged`: Informing when `CanExecute` evaluation changed. |
| 38 | + |
| 39 | +```cs |
| 40 | +public interface ICommand |
| 41 | +{ |
| 42 | + /// <summary>Occurs when changes occur that affect whether or not the command should execute.</summary> |
| 43 | + event EventHandler? CanExecuteChanged; |
| 44 | + |
| 45 | + /// <summary>Defines the method that determines whether the command can execute in its current state.</summary> |
| 46 | + /// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to <see langword="null" />.</param> |
| 47 | + /// <returns> |
| 48 | + /// <see langword="true" /> if this command can be executed; otherwise, <see langword="false" />.</returns> |
| 49 | + bool CanExecute(object? parameter); |
| 50 | + |
| 51 | + /// <summary>Defines the method to be called when the command is invoked.</summary> |
| 52 | + /// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to <see langword="null" />.</param> |
| 53 | + void Execute(object? parameter); |
| 54 | +} |
| 55 | +``` |
| 56 | + |
| 57 | +`IRelayCommand` in `CommunityToolkit` simply extends the `ICommand` with a new notify method. |
| 58 | +We do need a real implementation of how we inform on `CanExecuteChanged`, this is generally missing in .NET builtin event-driven interfaces. |
| 59 | + |
| 60 | +```cs |
| 61 | +public interface IRelayCommand : ICommand |
| 62 | +{ |
| 63 | + /// <summary> |
| 64 | + /// Notifies that the <see cref="ICommand.CanExecute"/> property has changed. // [!code highlight] |
| 65 | + /// </summary> |
| 66 | + void NotifyCanExecuteChanged(); |
| 67 | +} |
| 68 | +``` |
| 69 | + |
| 70 | +> [!NOTE] |
| 71 | +> `IRelayCommand` and `RelayCommand` have generic versions and async versions. |
| 72 | +
|
| 73 | +The type of generated field is `RelayCommand` which implements the `IRelayCommand`, this is essentially a base wrapper for the logic behind. |
| 74 | + |
| 75 | +```cs |
| 76 | +public sealed partial class RelayCommand : IRelayCommand |
| 77 | +{ |
| 78 | + /// <summary> |
| 79 | + /// The <see cref="Action"/> to invoke when <see cref="Execute"/> is used. |
| 80 | + /// </summary> |
| 81 | + private readonly Action execute; |
| 82 | + |
| 83 | + /// <summary> |
| 84 | + /// The optional action to invoke when <see cref="CanExecute"/> is used. |
| 85 | + /// </summary> |
| 86 | + private readonly Func<bool>? canExecute; |
| 87 | + |
| 88 | + /// <inheritdoc/> |
| 89 | + public event EventHandler? CanExecuteChanged; |
| 90 | + |
| 91 | + /// <summary> |
| 92 | + /// Initializes a new instance of the <see cref="RelayCommand"/> class that can always execute. |
| 93 | + /// </summary> |
| 94 | + /// <param name="execute">The execution logic.</param> |
| 95 | + /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="execute"/> is <see langword="null"/>.</exception> |
| 96 | + public RelayCommand(Action execute) |
| 97 | + { |
| 98 | + ArgumentNullException.ThrowIfNull(execute); |
| 99 | + |
| 100 | + this.execute = execute; |
| 101 | + } |
| 102 | + |
| 103 | + /// <summary> |
| 104 | + /// Initializes a new instance of the <see cref="RelayCommand"/> class. |
| 105 | + /// </summary> |
| 106 | + /// <param name="execute">The execution logic.</param> |
| 107 | + /// <param name="canExecute">The execution status logic.</param> |
| 108 | + /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="execute"/> or <paramref name="canExecute"/> are <see langword="null"/>.</exception> |
| 109 | + public RelayCommand(Action execute, Func<bool> canExecute) |
| 110 | + { |
| 111 | + ArgumentNullException.ThrowIfNull(execute); |
| 112 | + ArgumentNullException.ThrowIfNull(canExecute); |
| 113 | + |
| 114 | + this.execute = execute; |
| 115 | + this.canExecute = canExecute; |
| 116 | + } |
| 117 | + |
| 118 | + /// <inheritdoc/> |
| 119 | + public void NotifyCanExecuteChanged() |
| 120 | + { |
| 121 | + CanExecuteChanged?.Invoke(this, EventArgs.Empty); |
| 122 | + } |
| 123 | + |
| 124 | + /// <inheritdoc/> |
| 125 | + [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| 126 | + public bool CanExecute(object? parameter) |
| 127 | + { |
| 128 | + return this.canExecute?.Invoke() != false; |
| 129 | + } |
| 130 | + |
| 131 | + /// <inheritdoc/> |
| 132 | + public void Execute(object? parameter) |
| 133 | + { |
| 134 | + this.execute(); |
| 135 | + } |
| 136 | +} |
| 137 | +``` |
0 commit comments