Correctly Sorting/Filtering Collections in Flex: ListCollectionView
Posted by Joe Rinehart at 2:18 PM
2 comments - Categories:
Flex
When you're writing a small app, you're likely to have an ArrayCollection of Contacts or the like floating around in your components.
As that app grows, you're likely to move to MVC or ModelLocator, where your DataGrids and whatnot bind to a collection that's not necessary stored "inside" the component itself.
On one of these views, you'll have a ComboBox showing Contacts in the list.
On another view, you'll have a DataGrid showing the list of Contacts.
One day, someone will click one of the headers on the DataGrid to sort by something like Contact.dateOfBirth, and they'll ask why the Contacts in the ComboBox just resorted themselves: it's because both are bound to the same collection sharing the same sort and filter behaviors. Whoops!
Wouldn't it be great if Flex provided a class that was just a "wrapper" around another collection that applied its own sorts and filters?
Yep, it would, and even better, Flex does! The ListCollectionView is exactly what we need: it takes any implementation of ICollectionView as its "list" property, and implements the filterFunction and sort properties of ICollectionView, making it a wrapper on a collection that won't change the underlying collection's sort or filter!
Want an example? I've created a quick demo at http://firemoss.com/blogsamples/sortinglists/ that shows the bad behavior (the middle grid binds to the same ArrayCollection as the first) and the best practice implementation (the rightmost grid binds to a ListCollectionView wrapping the "true" data).
The sample data is the list of bikes currently in my garage.
Larry wrote on 08/22/08 10:51 PM
Thank you very much. You just saved me from workingall weekend. I knew that ListCollectionView existed, but
I didn't realize it did what it did. Until google found you,
I was contemplating a very complicated solution to
this.
I am updating a collection every second and displaying
that collection in a DataGrid, so before using
ListCollectionView, a user sort caused me problems.