MarcinNotos
MarcinNotos

Reputation: 11

When object property in ObservableCollection changed, notify another property, CommunityToolkit Mvvm

Class definition:

public partial class Pozycje: ObservableObject
{
   [ObservableProperty] private bool _ok;
   [ObservableProperty] private string _name;
   [ObservableProperty] private decimal _qty;
   [ObservableProperty] private decimal _val;
}

Collection and property definition:

public decimal Suma => Pozycja.Where(x => x.Ok).Sum(x=>x.Val+x.Qty);

private ObservableCollection<Pozycje> _poz;
public ObservableCollection<PozycjaObservable> Poz
{
    get => _poz;
    set
    {
      _poz = value;
      OnPropertyChanged();
      OnPropertyChanged(nameof(Suma));
   }
}

In Xaml:

 <Label Text="{Binding Suma}"/>

When I change "Poz" collection item property "Ok" Suma don't update.

Upvotes: 1

Views: 1927

Answers (1)

Jason
Jason

Reputation: 89092

Pozs setter is only called when Poz is assigned, NOT when items are added/removed

if you want to update Suma when an item is added or removed from Poz, you need to use Pozs CollectionChanged event

Poz.CollectionChanged += {
  OnPropertyChanged(nameof(Suma));
}

Upvotes: 1

Related Questions