Articles in categories

Articles

Notify ObservableCollection when an item's property has changed

Here's how I get a notification when an item's property in an ObservableCollection has been changed, not the ObservableCollection itself.

The object DisplayOrderItem is just some class which implements INotifyPropertyChanged.

A property of DisplayOrderItem example:

private Decimal _price;
public Decimal Price
{
	get { return _price; }
	set
	{
		if (value != _price)
		{
			_price = value;
			RaisePropertyChanged("Price");
		}
	}
}

 

Add an EventHandler to your ObservableCollection:

DisplayOrderItems = new ObservableCollection<DisplayOrderItem>();
DisplayOrderItems.CollectionChanged += DisplayOrderItemsChanged;

 

The CollectionChanged EventHandler method:

private void DisplayOrderItemsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
	if (e.NewItems != null)
		foreach (INotifyPropertyChanged item in e.NewItems)
			item.PropertyChanged += new PropertyChangedEventHandler(ItemPropertyChanged);

	if (e.OldItems != null)
		foreach (INotifyPropertyChanged item in e.OldItems)
	item.PropertyChanged -= new PropertyChangedEventHandler(ItemPropertyChanged);
}

 

The PropertyChangedEventHandler:

private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
	// Do what you need to do here
	foreach (var displayOrderItem in DisplayOrderItems)
	{
		TotalPrice += displayOrderItem.Price;
		TotalQuantity += displayOrderItem.Quantity;
	}
}

 Now when I say change the Price property of DisplayOrderItem in the collection a notification will be thrown and I can do something with it.