Windows Phone: ListBox ItemsSource and List

In Windows Phone development, you can always assigning List<T> collection to a ListBox through ItemSource. If and only if you never remove any item in the List<T> collection before you assign the ListBox ItemSource to null first.

ListBox.ItemSource = SomethingList;

I encounter a situation where I display a list of items in a ListBox on my main page. Then user can to select the item in ListBox and edit or delete the item on the next page. Adding new item to the list or edit the item in the list doesn’t cause any problem at all. But if user delete any item on the second page and go back to the main page, the app will encounter an unexceptional error on App.xmal.cs. The error message show “The parameter is incorrect”, which give me no hint or clue what actually go wrong. Searching on the web for the error message or -2147024809 code give me no result at all.

 

After many testing I only figure out the problem that I assigning a List<T> collection to a ListBox was a bad idea especially the item can be remove by user during runtime.  The main problem here is ListBox won’t have know what happen to the List<T> collection when some items got removed on the other pages and yet it continue to assign to those items. The solution is simple, just replace the List<T> collection to ObservableCollection<T> collection. The different between List<T> and  ObservableCollection<T> is  ObservableCollection<T> will tell ListBox something changed and it need to update instead of crashing the whole app.

Now the problem had solved, but it doesn’t mean ListBox ItemSource must assigned to ObservableCollection<T> instead of List<T>. If the list of items wanted to display doesn’t change through out the app lifetime, it is still better to use List<T> because of it’s simplicity which save you more processing and memory.

by Ooi Keng Siang (Microsoft Student Partners) via Ooiks’s Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s