Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...