2

我认为两者都是相同的,但是为什么两者都以相同的方法使用?我认为有一个细微的差别。这是一些代码来显示两者之间的区别:

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

我认为有区别,但我不确定。有人可以解释一下有什么区别吗?

4

1 回答 1

3

表示属性值已更改的PropertyChanged信号。该事件表明集合的内容已更改(不是集合本身:它仍然是相同的集合实例,但元素已被添加/删除/替换)。CollectionChanged

于 2012-05-20T02:18:42.037 回答