Monday, February 24, 2014

Swapped a ListBox for a LongListSelector and now the items don't show?

If you're not too distracted by all the announcements coming from MWC at the moment I thought I'd share this little gotcha that cost me more time than it should have.

I'm updating an app for a client at the moment and for one of the visual tweaks that I wanted to add meant I wanted to replace a ListBox with a LongListSelector.
All should be simple enough. It should just be a case of replacing this:

<ListBox ItemsSource="{Binding Sessions}">
            // ...

with this:

<phone:LongListSelector ItemsSource="{Binding Sessions}">
            // ...

All seemed good but then no items were shown on the page.

Well, it turns out that in the ViewModel the Sessions property was an IEnumerable<Session>.
For the LongListSelector to be able to load the items it needs the NotifyPropertyChanged events to be raised. The easiest way to do this was to change the Sessions property to be an ObservableCollection<Session>. This way the necessary events are raised and content is displayed. :)

Obvious really.
Hopefully this reminder will save someone else some head scratching in future.


  1. A collection of items will appear in the LLS w/o the collection being an ObservableCollection. Take the DataBoundApp sample. If you change the Items property of the MainViewModel to a List, or Collection items will still show provided that you notify the UI that the collection has changed. For the sample app it can be as simple as calling NotifyPropertyChanged("Items"); in the end of the LoadData method. If your collection already has data then the LLS will show without any problems.

    1. Thanks for the extra info Shawn. I just wanted to highlight the fact that ListBox and LongListSelector behave differently in this area.