2

どちらも同じだと思いますが、なぜ両方が同じ方法で使用されるのですか? 微妙な違いはあると思います。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 に答える