Aller au contenu

Exemple complet : liste de tâches

Tout ce qui précède, assemblé dans une petite application.

dotnet new avalonia.mvvm -o Taches
cd Taches

Fonctionnalités : ajouter (Enter), cocher, supprimer, filtrer, compteur, sauvegarde JSON.

Aperçu · essayez l'application (simulation HTML)
Tâches
Mes tâches
1 restante(s)

Modèle

Models/Tache.cs
using CommunityToolkit.Mvvm.ComponentModel;

namespace Taches.Models;

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

Service de stockage

Services/Stockage.cs
using System.Text.Json;
using Taches.Models;

namespace Taches.Services;

public class Stockage
{
    private static readonly string Chemin = Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Taches", "taches.json");

    public async Task<List<Tache>> ChargerAsync()
    {
        if (!File.Exists(Chemin)) return [];
        await using var flux = File.OpenRead(Chemin);
        return await JsonSerializer.DeserializeAsync<List<Tache>>(flux) ?? [];
    }

    private readonly SemaphoreSlim _verrou = new(1, 1);   // une écriture à la fois

    public async Task EnregistrerAsync(IEnumerable<Tache> taches)
    {
        var copie = taches.ToList();
        await _verrou.WaitAsync();
        try
        {
            Directory.CreateDirectory(Path.GetDirectoryName(Chemin)!);
            await using var flux = File.Create(Chemin);
            await JsonSerializer.SerializeAsync(flux, copie);
        }
        finally
        {
            _verrou.Release();
        }
    }
}

ViewModel

ViewModels/MainViewModel.cs
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Taches.Models;
using Taches.Services;

namespace Taches.ViewModels;

public enum Filtre { Toutes, Actives, Terminees }

public partial class MainViewModel : ObservableObject
{
    private readonly Stockage _stockage = new();

    public ObservableCollection<Tache> Taches { get; } = new();
    public ObservableCollection<Tache> Visibles { get; } = new();

    [ObservableProperty]
    [NotifyCanExecuteChangedFor(nameof(AjouterCommand))]
    public partial string NouveauTitre { get; set; } = "";

    [ObservableProperty]
    public partial Filtre FiltreCourant { get; set; } = Filtre.Toutes;

    public int Restantes => Taches.Count(t => !t.EstFaite);

    public MainViewModel()
    {
        Taches.CollectionChanged += OnCollectionChanged;
        _ = ChargerAsync();
    }

    private async Task ChargerAsync()
    {
        foreach (var t in await _stockage.ChargerAsync()) Taches.Add(t);
    }

    [RelayCommand(CanExecute = nameof(PeutAjouter))]
    private void Ajouter()
    {
        Taches.Add(new Tache { Titre = NouveauTitre.Trim() });
        NouveauTitre = "";
    }

    private bool PeutAjouter() => !string.IsNullOrWhiteSpace(NouveauTitre);

    [RelayCommand]
    private void Supprimer(Tache tache) => Taches.Remove(tache);

    [RelayCommand]
    private void ViderTerminees()
    {
        foreach (var t in Taches.Where(t => t.EstFaite).ToList()) Taches.Remove(t);
    }

    partial void OnFiltreCourantChanged(Filtre value) => Rafraichir();

    private void OnCollectionChanged(object? s, NotifyCollectionChangedEventArgs e)
    {
        foreach (Tache t in e.NewItems ?? Array.Empty<Tache>()) t.PropertyChanged += OnTacheChanged;
        foreach (Tache t in e.OldItems ?? Array.Empty<Tache>()) t.PropertyChanged -= OnTacheChanged;
        Rafraichir();
    }

    private void OnTacheChanged(object? s, PropertyChangedEventArgs e) => Rafraichir();

    private async void Rafraichir()
    {
        Visibles.Clear();
        foreach (var t in Taches.Where(t => FiltreCourant switch
                 {
                     Filtre.Actives => !t.EstFaite,
                     Filtre.Terminees => t.EstFaite,
                     _ => true
                 }))
            Visibles.Add(t);

        OnPropertyChanged(nameof(Restantes));
        await _stockage.EnregistrerAsync(Taches);
    }
}

Vue

Views/MainWindow.axaml
<Window xmlns="https://github.com/avaloniaui"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="using:Taches.ViewModels"
        xmlns:m="using:Taches.Models"
        x:Class="Taches.Views.MainWindow"
        x:DataType="vm:MainViewModel"
        Title="Tâches" Width="480" Height="640"
        WindowStartupLocation="CenterScreen">

  <Window.Styles>
    <Style Selector="TextBlock.faite">
      <Setter Property="TextDecorations" Value="Strikethrough" />
      <Setter Property="Opacity" Value="0.5" />
    </Style>
  </Window.Styles>

  <Grid RowDefinitions="Auto,Auto,*,Auto" Margin="20" RowSpacing="12">

    <TextBlock Text="Mes tâches" FontSize="28" FontWeight="Bold" />

    <!-- Saisie -->
    <TextBox Grid.Row="1" Text="{Binding NouveauTitre}" PlaceholderText="Que faut-il faire ?">
      <TextBox.KeyBindings>
        <KeyBinding Gesture="Enter" Command="{Binding AjouterCommand}" />
      </TextBox.KeyBindings>
      <TextBox.InnerRightContent>
        <Button Content="Ajouter" Command="{Binding AjouterCommand}" Classes="accent" Margin="4" />
      </TextBox.InnerRightContent>
    </TextBox>

    <!-- Liste -->
    <Panel Grid.Row="2">
      <ListBox ItemsSource="{Binding Visibles}">
        <ListBox.ItemTemplate>
          <DataTemplate x:DataType="m:Tache">
            <DockPanel>
              <Button DockPanel.Dock="Right" Content="✕" Background="Transparent"
                      Command="{Binding $parent[ListBox].((vm:MainViewModel)DataContext).SupprimerCommand}"
                      CommandParameter="{Binding}" />
              <StackPanel Orientation="Horizontal" Spacing="8">
                <CheckBox IsChecked="{Binding EstFaite}" />
                <TextBlock Text="{Binding Titre}" VerticalAlignment="Center"
                           Classes.faite="{Binding EstFaite}" />
              </StackPanel>
            </DockPanel>
          </DataTemplate>
        </ListBox.ItemTemplate>
      </ListBox>

      <TextBlock Text="Rien à faire 🎉" Opacity="0.5"
                 HorizontalAlignment="Center" VerticalAlignment="Center"
                 IsVisible="{Binding !Visibles.Count}" />
    </Panel>

    <!-- Pied -->
    <DockPanel Grid.Row="3">
      <Button DockPanel.Dock="Right" Content="Vider les terminées"
              Command="{Binding ViderTermineesCommand}" />
      <ComboBox DockPanel.Dock="Right" Margin="0,0,8,0" Width="120"
                ItemsSource="{x:Static vm:MainViewModel.Filtres}"
                SelectedItem="{Binding FiltreCourant}" />
      <TextBlock Text="{Binding Restantes, StringFormat='{}{0} restante(s)'}"
                 VerticalAlignment="Center" />
    </DockPanel>
  </Grid>
</Window>

Ajoutez la liste des filtres pour la ComboBox :

ViewModels/MainViewModel.cs
public static Filtre[] Filtres { get; } = Enum.GetValues<Filtre>();

Branchement

App.axaml.cs
desktop.MainWindow = new MainWindow { DataContext = new MainViewModel() };
dotnet run

Pour aller plus loin