WPF

ListBox, ScrollIntoView and ObservableCollection vs. ICollectionView

February 14, 2011 · 1 min read

I almost struggled with a somewhat SEO-friendly title for this but considering I've had at least one request for an explanation, I thought I'd try to post my thoughts in a blog format. The twitter shotgun of a couple of 140 character posts wasn't enough to really convey what was happening.

To set the scene a little bit, I'm making a IRC client for WP7 and one of the core requirements (to me) is "automatically scroll to bottom on output". To achieve this, the ScrollIntoView() method for certain controls like ListBox, ListView, or DataGrid is absolutely crucial. I use MVVMLight and subscribe to an approach of triggering the code-behind from the ViewModel usually through a property update. In this case I chose binding the ListBox's SelectedItem and wired up the SelectionChanged event with code that basically said "when your selection changes, scroll to that since I'm pretty sure that bit of information is what my users (and I) want to see."

The events only fire when something is on screen, which is a tell-tale sign of virtualization to me, and I needed some way around it safely while still utilizing virtualization if possible. The rescue comes in the form of binding the ItemsSource to ICollectionView instead of ObservableCollection as it gives us the MoveCurrentTo() methods as well as filter, sort, and grouping capabilities. When you call MoveCurrentTo, virtualization is turned off so that SelectionChanged can then fire and finish the job.

I will say that ICollectionView is a bit more overhead than most people need which is probably why it isn't pushed as much in samples but I pretty much never bind directly to ObservableCollection anymore.