Search code examples
c#wpfmvvmdata-bindingprism

Notify item changes in observable collection in WPF/C#


In my WPF project, i have a Service EF model defined as

public class Service
{
  public int ID
  public string Name
  public decimal Price
}

and in my viewmodel i have.

public class ReceiptViewModel : BindableBase
{
    private ObservableCollection<Service> _services;
    public ObservableCollection<Service> Services
    {
        get { return _services; }
        set { SetProperty(ref _services, value, () => RaisePropertyChanged(nameof(Total))); }
    }

    public decimal Total => Services.Sum(s => s.Price);
}

Total is bound to a textblock in my view and and my observable collection is bound to an itemscontrol with textbox inside.

i want my Total textblock to change everytime the user change one of the price in my collection from the UI. how can i achieve that?


Solution

  • You should implement it yourself, my example of observable collection (and also you need to subscribe and Raise OnPropertyChanged(nameof(Total))) when collection item was changed, or change my implementation of collectionEx to raising collection changed event.

        public class ObservableCollectionEx<T> : ObservableCollection<T> where T : INotifyPropertyChanged
    {
      public ObservableCollectionEx(IEnumerable<T> initialData) : base(initialData)
      {
          Init();
      }
    
      public ObservableCollectionEx()
      {
          Init();
      }
    
      private void Init()
      {
          foreach (T item in Items)
             item.PropertyChanged += ItemOnPropertyChanged;
    
          CollectionChanged += FullObservableCollectionCollectionChanged;
      }
    
      private void FullObservableCollectionCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
      {
          if (e.NewItems != null)
          {
             foreach (T item in e.NewItems)
             {
                if (item != null)
                   item.PropertyChanged += ItemOnPropertyChanged;
             }
          }
    
          if (e.OldItems != null)
          {
              foreach (T item in e.OldItems)
              {
                  if (item != null)
                      item.PropertyChanged -= ItemOnPropertyChanged;
              }
          }
      }
    
        private void ItemOnPropertyChanged(object sender, PropertyChangedEventArgs e)
            => ItemChanged?.Invoke(sender, e);
    
        public event PropertyChangedEventHandler ItemChanged;
    }