Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...