Aller au contenu

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 = "";
}
<Button Content="Effacer" Command="{Binding EffacerCommand}" />

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

[RelayCommand]
private void Supprimer(Tache tache) => Taches.Remove(tache);
<Button Content="✕" Command="{Binding SupprimerCommand}" CommandParameter="{Binding SelectedTache}" />

Asynchrone

[RelayCommand]
private async Task ChargerAsync()
{
    Clients = await _api.GetClientsAsync();
}

ChargerAsync → ChargerCommand (le suffixe Async est retiré). Pendant l'exécution, la commande est désactivée et ChargerCommand.IsRunning vaut true.

Aperçu · cliquez : 2 s de chargement simulé
<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

[RelayCommand(AllowConcurrentExecutions = true)]
private async Task PingAsync() { /* … */ }

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.

Aperçu · tapez un message
flowchart LR
  M["Message change"] --> N["NotifyCanExecuteChangedFor"] --> C["EnvoyerCommand<br/>réévalue PeutEnvoyer()"] --> B["Button.IsEnabled"]

Rafraîchir manuellement

EnvoyerCommand.NotifyCanExecuteChanged();

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

<MenuItem Header="_Enregistrer" Command="{Binding EnregistrerCommand}" InputGesture="Ctrl+S" />

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 :

public void Ouvrir(string nom) { /* … */ }
<Button Content="Ouvrir" Command="{Binding Ouvrir}" CommandParameter="rapport.pdf" />

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);
}