Commandes¶
Une commande = une action du ViewModel, liée à un bouton, un menu ou un raccourci.
[RelayCommand]¶
public partial class EditeurViewModel : ObservableObject
{
[RelayCommand]
private void Effacer() => Texte = "";
}
Le générateur crée EffacerCommand (nom de la méthode + Command).
sequenceDiagram
participant B as Button
participant C as EffacerCommand
participant VM as Effacer()
B->>C: CanExecute ? → active / grisé
Note over B: clic
B->>C: Execute(CommandParameter)
C->>VM: appelle la méthode
Avec paramètre¶
<Button Content="✕" Command="{Binding SupprimerCommand}" CommandParameter="{Binding SelectedTache}" />
Asynchrone¶
ChargerAsync → ChargerCommand (le suffixe Async est retiré). Pendant l'exécution, la commande est
désactivée et ChargerCommand.IsRunning vaut true.
<Button Content="Charger" Command="{Binding ChargerCommand}" />
<ProgressBar IsIndeterminate="True" IsVisible="{Binding ChargerCommand.IsRunning}" />
Annulation¶
[RelayCommand(IncludeCancelCommand = true)]
private async Task TelechargerAsync(CancellationToken jeton)
{
await _service.TelechargerAsync(jeton);
}
<Button Content="Télécharger" Command="{Binding TelechargerCommand}" />
<Button Content="Annuler" Command="{Binding TelechargerCancelCommand}" />
Autoriser plusieurs exécutions simultanées¶
CanExecute¶
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(EnvoyerCommand))]
public partial string Message { get; set; } = "";
[RelayCommand(CanExecute = nameof(PeutEnvoyer))]
private async Task EnvoyerAsync() => await _chat.EnvoyerAsync(Message);
private bool PeutEnvoyer() => !string.IsNullOrWhiteSpace(Message);
Le bouton se désactive tout seul quand PeutEnvoyer() renvoie false.
flowchart LR
M["Message change"] --> N["NotifyCanExecuteChangedFor"] --> C["EnvoyerCommand<br/>réévalue PeutEnvoyer()"] --> B["Button.IsEnabled"]
Rafraîchir manuellement¶
Raccourcis clavier¶
<Window.KeyBindings>
<KeyBinding Gesture="Ctrl+S" Command="{Binding EnregistrerCommand}" />
<KeyBinding Gesture="Ctrl+Shift+N" Command="{Binding NouveauCommand}" />
<KeyBinding Gesture="Delete" Command="{Binding SupprimerCommand}" CommandParameter="{Binding Selection}" />
</Window.KeyBindings>
Dans un menu¶
Entrée dans un champ¶
<TextBox Text="{Binding Message}">
<TextBox.KeyBindings>
<KeyBinding Gesture="Enter" Command="{Binding EnvoyerCommand}" />
</TextBox.KeyBindings>
</TextBox>
Lier une méthode directement¶
Sans attribut, Avalonia peut appeler une méthode publique :
Tip
Pratique pour un prototype. Préférez [RelayCommand] : CanExecute, async et testabilité.
Commande sans toolkit¶
public class Commande(Action<object?> executer, Func<object?, bool>? peut = null) : ICommand
{
public event EventHandler? CanExecuteChanged;
public bool CanExecute(object? p) => peut?.Invoke(p) ?? true;
public void Execute(object? p) => executer(p);
public void Rafraichir() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}