I have developed a wpf application to load images in listbox.To load 300mb images it is taking time.I heard that to load images faster in listbox we have to use observablecollection,but i dont know how to use that one. Any suggestions plz.. Thanks in advance
views:
663answers:
3An ObservableCollection can be used exactly like a List. But it won't help loading the images faster...
What you should do is bind your ListBox to an ObservableCollection containing the images, and fill the collection with the images in a separate thread. It is normally not possible to modify a bound collection from another thread, but I wrote an AsyncObservableCollection class which can handle this issue.
Just moving your images into an ObservableCollection
won't magically make them load faster. What is likely taking so long is the loading of the image data from disk. You should move this to a background thread so that the main UI thread won't be hung while loading the image data. Look into using either BackgroundWorker or Dispatcher so that you don't have to write all of the threading code yourself.
You only need ObservableCollection if you'll be adding/removing/replacing items in the collection and expecting the UI to automatically update with those changes. That said, ObservableCollection would be perfect for Thomas or Andy's suggestion of loading in a background thread.
Here's another possibility worth mentioning, though it has limitations. ListBox only creates UI elements for the list items that are currently scrolled into view. If only a small number of images will be visible in the listbox at a time, and the others will all be scrolled out of view, then you could take advantage of this, and have the ListBox just lazy-load the images.
For this, you wouldn't put actual image objects in the ListBox. Instead, you would put something that can load the image on demand. If you're loading the images from disk or from the Web, the list could contain Uris. If you're doing something fancier like loading from a Web service, the list could contain instances of a class with an Image property that lazy-loads the image.
Then bind your collection (any list, not necessarily an ObservableCollection) to the ListBox, and set the ItemTemplate to a DataTemplate that constructs the appropriate UI and binds to the Uri or to the lazy-loading Image property.
Upside: Simplicity. No need to write threading code.
Downsides: It would depend on the amount of data, but this would probably make scrolling slow, since the later images wouldn't load until you start scrolling. Also, as I noted, if most of the images fit in the ListBox when it's first shown, this wouldn't gain you much, and threading would be a better answer. And the Uri has a big gotcha, in that once you've scrolled down, the ListBox will throw away the images that it loaded for the first items, so scrolling back up would be just as slow as scrolling down (though a custom class with a lazy-loading property would fix this).