MVVM 监听List数量变化、子项属性值变化

   private async void FreshQr(object? state)
    {
        if (!RouterAsyncHelper.GetActivateRouterName().Equals(RouterPathConst.AlbumView)) return;
        var qrCollection = _dbContext._Database.GetCollection<QrEntity>();
        var photoCollection = _dbContext._Database.GetCollection<PhotoEntity>();

        // 获取需要更新的 PhotoId
        var uploadingQrIds = qrCollection.Find(x => x.FilePath == ApplicationConst.FileUploading)
            .Select(x => x.PhotoId)
            .ToList();

        // 直接查询需要更新的 PhotoEntity
        var photoIdsToUpdate = Vo.PhotoList.Where(p => 
            !uploadingQrIds.Contains(p.Id) && 
            p.QrPath == ApplicationConst.FileUploading
        ).Select(p => p.Id).ToList();

        var newPhotos = photoCollection.Find(p => 
            photoIdsToUpdate.Contains(p.Id) && 
            !p.Delete
        ).ToDictionary(p => p.Id);
        var photoList = Vo.PhotoList.ToList();
        foreach (var photo in photoList) // ToList避免枚举修改
        {
            if (newPhotos.TryGetValue(photo.Id, out var newPhoto))
            {
                var index = Vo.PhotoList.IndexOf(photo);
                if (index >= 0)
                {
                   await Application.Current.Dispatcher.InvokeAsync(() =>
                   {
                       Vo.PhotoList.RemoveAt(index);
                       Vo.PhotoList.Insert(index,newPhoto);
                   });
                }
            }
        }
    }

   ~AlbumViewModel()
    {
        Vo.PhotoList.CollectionChanged -= PhotoListItemChange;
        WeakReferenceMessenger.Default.UnregisterAll(this);
    }

   Vo.PhotoList.CollectionChanged += PhotoListItemChange;

    private async void PhotoListItemChange(object? sender, NotifyCollectionChangedEventArgs e)
    {
        await Application.Current.Dispatcher.InvokeAsync(() =>
        {
            if (Vo.PhotoList.Count > 0)
                // _logger.LogInformation($"相册数量为:{Vo.PhotoList.Count}");
                Vo.BackgroundPath = "../Resources/Images/background.png";
            else
                // _logger.LogInformation("相册数量为:0");
                Vo.BackgroundPath = "../Resources/Images/background-empty.png";
        });
    }
    
posted @ 2026-02-03 10:12  Timskt  阅读(7)  评论(0)    收藏  举报