Hi, quick tip for WPF. I’m set to leave for my 2 week vacation today, so this will be a quick one.
I was building a physics simulation in WPF (still to be completed), and as usual I binded my ObservableCollection to a Custom Canvas control, which I specified in my ItemsControl‘s ItemPanelTemplate. If you have noticed, all the WPF “container” controls like ListBox, ItemsControl, etc all have an ItemsSource propery where you can specify your data source. So what happens when I add/remove something from that data source, how do I get notified???
I did some digging around, but realised there’s no such event that gets triggered. The trick is to look at the the Items property, which is of type System.Windows.Controls.ItemCollection. It inherits from a CollectionView, which implements the INotifyCollectionChanged interface, which has the CollectionChanged event. Bingo, here we go…
This is sample code that demonstrates how to use this.
((INotifyCollectionChanged)itemsControl.Items).CollectionChanged += new NotifyCollectionChangedEventHandler(Window1_CollectionChanged);
itemsControl.ItemsSource = particles;
void Window1_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
if (e.Action == NotifyCollectionChangedAction.Add)
// do something
So you will now be notified of changes in your control’s Items due to changes in your data source. You might also want to learn more about the NotifyCollectionChangedEventArgs, it has some useful properties in there. Also you should have a look at NotifyCollectionChangeAction enum values to learn more about what kind of notification actions are available.