PropertyChangedEventHandler 和 NotifyCollectionChangedEventHa
本文关键字:NotifyCollectionChangedEventHa PropertyChangedEventHandler | 更新日期: 2023-09-27 18:34:46
我认为两者都是一样的,但为什么两者都以相同的方法使用?我认为有一个细微的区别。下面是一些代码来显示两者之间的区别:
private void LoadItemListing()
{
_items = new ObservableCollection<SalesItemListingViewModel>();
foreach (ItemListing x in _sales.Items)
{
SalesItemListingViewModel itemListing = new SalesItemListingViewModel(x);
_items.Add(itemListing);
_itemAmountSum += itemListing.Amount;
itemListing.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(itemListing_PropertyChanged);
}
_items.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_items_CollectionChanged);
}
对于itemListing_PropertyChanged:
void itemListing_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == "Amount")
{
ItemAmountSum = 0;
foreach (SalesItemListingViewModel x in Items)
ItemAmountSum += x.Amount;
}
}
而这段代码_items_CollectionChanged:
void _items_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
{
SalesItemListingViewModel newItemListingViewModel = e.NewItems[0] as SalesItemListingViewModel;
newItemListingViewModel.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(itemListing_PropertyChanged);
}
else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
{
ItemAmountSum = 0;
foreach (SalesItemListingViewModel x in Items)
ItemAmountSum += x.Amount;
}
RaisePropertyChanged("Items");
}
我认为有区别,但我不确定。有人可以解释一下任何区别吗?
PropertyChanged
表示属性的值已更改。CollectionChanged
事件表示集合的内容已更改(不是集合本身:它仍然是相同的集合实例,但元素已被添加/删除/替换(。