Aller au contenu

MVVM Toolkit

CommunityToolkit.Mvvm génère le code répétitif : notifications, commandes, messages.

dotnet add package CommunityToolkit.Mvvm

Propriété observable

using CommunityToolkit.Mvvm.ComponentModel;

public partial class ProfilViewModel : ObservableObject
{
    [ObservableProperty]
    public partial string Nom { get; set; } = "";

    [ObservableProperty]
    public partial int Age { get; set; }
}

La classe et la propriété doivent être partial. Le générateur écrit le setter qui notifie la vue.

flowchart LR
  V["Vous écrivez<br/>[ObservableProperty]<br/>public partial string Nom"] -- "à la compilation" --> G["Générateur du toolkit"]
  G --> S["setter :<br/>si la valeur change →<br/>OnNomChanging/Changed<br/>+ PropertyChanged('Nom')"]
Ce que ça remplace
private string _nom = "";
public string Nom
{
    get => _nom;
    set => SetProperty(ref _nom, value);
}

Syntaxe champ

Les anciennes versions du toolkit utilisaient un champ : [ObservableProperty] private string _nom;. La syntaxe propriété partielle (C# 13+, .NET 9+ SDK) est recommandée.

Propriétés dépendantes

[ObservableProperty]
[NotifyPropertyChangedFor(nameof(NomComplet))]
public partial string Prenom { get; set; } = "";

[ObservableProperty]
[NotifyPropertyChangedFor(nameof(NomComplet))]
public partial string Nom { get; set; } = "";

public string NomComplet => $"{Prenom} {Nom}".Trim();
Aperçu · NomComplet se met à jour quand Prenom ou Nom change
NomComplet : Ada Lovelace
flowchart LR
  P["Prenom change"] --> N1["PropertyChanged('Prenom')"]
  P --> N2["PropertyChanged('NomComplet')<br/>grâce à NotifyPropertyChangedFor"]
  N2 --> T["TextBlock {Binding NomComplet}<br/>se rafraîchit"]

Réagir à un changement

[ObservableProperty]
public partial string Recherche { get; set; } = "";

partial void OnRechercheChanged(string value) => Filtrer(value);

// Ancienne et nouvelle valeur
partial void OnRechercheChanged(string? oldValue, string newValue) { }

// Avant le changement
partial void OnRechercheChanging(string value) { }

Activer / désactiver une commande

[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(EnregistrerCommand))]
public partial bool EstModifie { get; set; }

[RelayCommand(CanExecute = nameof(EstModifie))]
private void Enregistrer() { /* … */ }

Voir Commandes.

Classe de base commune

public abstract partial class ViewModelBase : ObservableObject
{
    [ObservableProperty]
    public partial bool EstOccupe { get; set; }

    protected async Task OccupeAsync(Func<Task> action)
    {
        EstOccupe = true;
        try { await action(); }
        finally { EstOccupe = false; }
    }
}
public partial class ClientsViewModel : ViewModelBase
{
    [RelayCommand]
    private Task ChargerAsync() => OccupeAsync(async () => Clients = await _api.GetClientsAsync());
}

Notifier manuellement

OnPropertyChanged(nameof(Total));
OnPropertyChanged(string.Empty);   // toutes les propriétés

Modèle observable

Un modèle affiché et modifié dans une liste doit aussi notifier :

public partial class Tache : ObservableObject
{
    [ObservableProperty] public partial string Titre { get; set; } = "";
    [ObservableProperty] public partial bool EstFaite { get; set; }
}

Messages entre ViewModels

flowchart LR
  E["EditionViewModel"] -- "Send(ClientModifie)" --> M(("WeakReferenceMessenger"))
  M -- "Receive" --> L["ListeViewModel"]
  M -- "Receive" --> S["StatistiquesViewModel"]

Les ViewModels ne se connaissent pas : ils passent par le messager.

using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.Mvvm.Messaging.Messages;

public sealed class ClientModifie(Client client) : ValueChangedMessage<Client>(client);
// Émetteur
WeakReferenceMessenger.Default.Send(new ClientModifie(client));

// Récepteur
public partial class ListeViewModel : ObservableRecipient, IRecipient<ClientModifie>
{
    public ListeViewModel() => IsActive = true;   // s'abonne

    public void Receive(ClientModifie message) => Rafraichir(message.Value);
}

Sans toolkit

public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;

    protected bool Set<T>(ref T champ, T valeur, [CallerMemberName] string? nom = null)
    {
        if (EqualityComparer<T>.Default.Equals(champ, valeur)) return false;
        champ = valeur;
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nom));
        return true;
    }
}

public class ProfilViewModel : ViewModelBase
{
    private string _nom = "";
    public string Nom { get => _nom; set => Set(ref _nom, value); }
}