如何更好地编写此代码:
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;
}
}
}
}
答案 0 :(得分:6)
e.Action == NotifyCollectionChangedAction.Remove
需要迭代e.OldItems
而不是e.NewItems
。e.Action == NotifyCollectionChangedAction.Replace
需要迭代e.OldItems
以从旧项中删除事件处理程序时,您需要迭代e.NewItems
以将事件处理程序添加到新项目中。< / LI>
重构代码如下:
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;
}
}
}
这很有效,因为所有的Promotion类都实现了INotifyPropertyChanged
。