using Avalonia.Threading; using CommunityToolkit.Mvvm.ComponentModel; using System.Collections.ObjectModel; namespace LehrerApp.Desktop.Services; public enum NotificationKind { Success, Error } /// /// Einheitliche Erfolgs-/Fehlermeldungen als Toast (13.2.3). Wird im MainWindow als /// Overlay über der aktuellen Seite angezeigt und blendet sich nach kurzer Zeit selbst aus. /// public class NotificationService { public ObservableCollection Toasts { get; } = []; public void ShowSuccess(string message) => Show(message, NotificationKind.Success, TimeSpan.FromSeconds(3)); public void ShowError(string message) => Show(message, NotificationKind.Error, TimeSpan.FromSeconds(6)); private void Show(string message, NotificationKind kind, TimeSpan duration) { void AddAndScheduleRemoval() { var toast = new ToastItem(message, kind); Toasts.Add(toast); _ = RemoveAfter(toast, duration); } if (Dispatcher.UIThread.CheckAccess()) AddAndScheduleRemoval(); else Dispatcher.UIThread.Post(AddAndScheduleRemoval); } private async Task RemoveAfter(ToastItem toast, TimeSpan duration) { await Task.Delay(duration); Toasts.Remove(toast); } } public partial class ToastItem : ObservableObject { public string Message { get; } public NotificationKind Kind { get; } public bool IsError => Kind == NotificationKind.Error; public ToastItem(string message, NotificationKind kind) { Message = message; Kind = kind; } }