How to load an image into ObservableCollection "on demand"?
-
2006年10月5日 下午 12:39
i have the following problem:
I have created an observableCollection that holds images fetched from the internet. The observableCollection contains a thumbnail photo and the original photo. I present only thmbnails of a photo and when user doubleclicks it, the original photo is shown. The thumbnails are shown in a WPF listbox control.
The problem is that the original images are large and it takes quite some time to load all of them into the ImageObjects (part of the observable collection). What I would like to achieve is to somehow load the large images "on demand". Is there a way of doing this?
In the photosCollection constructor I add an Photo object (which holds information about images... title, description, link to ti, ImageSource - thumbnail and largePhoto). In the photo object constructor I initialize all this values...
photoURL = ("................................");
thumbNailPhoto = ImageFromString(photoURL);
photoURL = ("..............................");
largePhoto = ImageFromString(photoURL);And here is the code for ImageFromString method...
public ImageSource ImageFromString(string url)
{
BitmapImage image = null;
if (this.photoURL != null)
{
image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(url);
image.EndInit();
}
return image;
}The definitions of the Photo class is as follows:
public class PhotosCollection
{..............
private ObservableCollection<Photo> photos = new ObservableCollection<Photo>();
.......................
public PhotosCollection() {
...................................
photos.Add(new Photo((string)photoDataTable.Rows
[0], (string)photoDataTable.Rows
[1], (string)photoDataTable.Rows
[2], (string)photoDataTable.Rows
[3], (string)photoDataTable.Rows
[4]));
...........................
}
..............................
}
Any help on this issue is greatly appreciated.....Thanks,
- Marko
所有回覆
-
2006年10月5日 下午 08:46?
-
2006年10月5日 下午 09:19
You could make the properties in your Photo class use lazy initialization to load the BitmapImages on demand. When you need to access a large version of an image, the getter for the property will check if the image has already been loaded, if not, then load the image. Don't use up-front initialization (i.e. loading images in a constructor).

