using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; namespace LibBeatmapDownload; public class DownloadTaskList : INotifyPropertyChanged { public DownloadTaskList() { Tasks.CollectionChanged += (sender, args) => { if (args.NewItems is { Count: > 0 }) foreach (var downloadTask in args.NewItems) { if (downloadTask is not DownloadTask task) { Debug.WriteLine($"[DownloadTaskList] New task is {downloadTask?.GetType().FullName ?? "null"}!"); continue; } task.PropertyChanged += (taskSender, taskArgs) => { if (taskArgs.PropertyName == nameof(DownloadTask.Status)) { if (task.Status == Status.Finished) { Task.Run(async () => { await Task.Delay(1000); Tasks.Remove(task); }); } SetField(ref _tasks, new ObservableCollection( _tasks .OrderByDescending(x => x.Progress) .ThenByDescending(x => x.Status) ), nameof(Tasks)); OnPropertyChanged(nameof(Tasks)); } }; } // OnPropertyChanged(nameof(Tasks)); }; } public event PropertyChangedEventHandler? PropertyChanged; private ObservableCollection _tasks = new(); public ObservableCollection Tasks { get => _tasks; set => SetField(ref _tasks, value); } protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } protected bool SetField(ref T field, T value, [CallerMemberName] string? propertyName = null) { //check ObservableCollection by order if (EqualityComparer.Default.Equals(field, value)) return false; field = value; OnPropertyChanged(propertyName); return true; } }