When working with collections attached to the user interface in WPF, there is a little trick that you should be aware of. Consider the source code of the Z09_ObservableCollections project in the WpfWednesday repository. On the MainWindow user interface, the left and the right of the panel looks the same – not counting the difference in the button captions.
The only difference is that the ListBox on the left is attached to a List of integers, while the ListBox on the right is attached to an ObservableCollection of integers. Both buttons are handling the click events in a way that they grab the last item from the item source of the ListBox above them, add one to it and append it to the item source.
When you click on the left button, nothing seems to happen. If you debug into the code, by placing a breakpoint on line 21 in MainWindow.xaml.cs, you will see that it is being hit and the list is properly extended. On the other hand, if you click on button on the right, everything seems to work fine. Why?
The reason lies in the fact that the ObservableCollection class is capable of emitting events describing any change in its content. When you bind a class capable of handling a collection from the .NET Framework, they check if the collection is an ObservableCollection. If the collection is in fact an ObservableCollection, they also attach event handlers to react to the events coming from the collection.
So, if the ObservableCollection can describe the changes related to it, what types of changes can it describe?
Pretty much everything. Here is the list:
- Addition of an item,
- Move of an item,
- Removal of an item,
- Replacement of an item,
- And the collection being reset to a totally new item collection.
Just by handling these events, you can keep any other relevant list up-to-date. In fact, if that is your goal, here is a small library that I’ve written to achieve that: https://github.com/atzimler/CollectionObservers . It was originally published as part of my MVVM library, but extracted it, so the MVVM logic can be excluded from the project. You can find it as a Portable Library (PCL) NuGet package.
No comments yet.