在WPF/C#中的可观察集合中通知项目更改 [英] Notify item changes in observable collection in WPF/C#

查看:80
本文介绍了在WPF/C#中的可观察集合中通知项目更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的WPF项目中,我有一个 Service EF模型定义为

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

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

在我的视图模型中.

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绑定到我的视图中的一个文本块,而我的可观察集合绑定到一个内部带有文本框的items控件.

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

我希望每次用户从UI更改集合中的价格之一时,Total文本块都会更改.我该如何实现?

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?

推荐答案

更改集合项时,您应该自己实现它,这是我的可观察集合的示例(并且您还需要订阅并提高OnPropertyChanged(nameof(Total))),或将我对collectionEx的实现更改为引发集合更改事件.

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

这篇关于在WPF/C#中的可观察集合中通知项目更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆