How can write this code better:
void CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (sender is ObservableCollection<PromotionPurchaseAmount>)
{
if (e.Action == NotifyCollectionChangedAction.Remove)
{
foreach (PromotionPurchaseAmount item in e.NewItems)
{
//Removed items
item.PropertyChanged -= EntityViewModelPropertyChanged;
}
}
else if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (PromotionPurchaseAmount item in e.NewItems)
{
//Added items
item.PropertyChanged += EntityViewModelPropertyChanged;
}
}
}
else if (sender is ObservableCollection<PromotionItemPricing>)
{
if (e.Action == NotifyCollectionChangedAction.Remove)
{
foreach (PromotionItemPricing item in e.NewItems)
{
//Removed items
item.PropertyChanged -= EntityViewModelPropertyChanged;
}
}
else if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (PromotionItemPricing item in e.NewItems)
{
//Added items
item.PropertyChanged += EntityViewModelPropertyChanged;
}
}
}
else if (sender is ObservableCollection<PromotionItem>)
{
if (e.Action == NotifyCollectionChangedAction.Remove)
{
foreach (PromotionItem item in e.NewItems)
{
//Removed items
item.PropertyChanged -= EntityViewModelPropertyChanged;
}
}
else if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (PromotionItem item in e.NewItems)
{
//Added items
item.PropertyChanged += EntityViewModelPropertyChanged;
}
}
}
}
- When
e.Action == NotifyCollectionChangedAction.Remove
you need to iterate overe.OldItems
instead ofe.NewItems
. - When
e.Action == NotifyCollectionChangedAction.Replace
you need to iterate overe.OldItems
to remove the event handler from the old items and you need to iterate overe.NewItems
to add the event handler to the new items. Refactor the code like this:
if (sender is ObservableCollection<PromotionPurchaseAmount> || sender is ObservableCollection<PromotionItemPricing> || sender is ObservableCollection<PromotionItem>) { if (e.Action == NotifyCollectionChangedAction.Remove || e.Action == NotifyCollectionChangedAction.Replace) { foreach (INotifyPropertyChanged item in e.OldItems) { //Removed items item.PropertyChanged -= EntityViewModelPropertyChanged; } } if (e.Action == NotifyCollectionChangedAction.Add || e.Action == NotifyCollectionChangedAction.Replace) { foreach (INotifyPropertyChanged item in e.NewItems) { //Added items item.PropertyChanged += EntityViewModelPropertyChanged; } } }
This works, because all of your Promotion classes implement INotifyPropertyChanged
.
精彩评论