I have a collection of custom objects called DataItems which contain URIs of images that I want to load and put in a collection for my Silverlight application to use.
As I process each DataItem, I get its SourceUri (e.g. "http://..../picture001.png") and start it loading:
void LoadNext()
{
WebClient webClientImgDownloader = new WebClient();
if (loadedItemIndex < RegisteredDataEntries.Count())
{
DataItem dataItem = RegisteredDataEntries[registeredIdCodes[loadedItemIndex]];
if (dataItem.Kind == DataItemKind.Image)
{
webClientImgDownloader.OpenReadCompleted +=
new OpenReadCompletedEventHandler(webClientImgDownloader_OpenReadCompleted);
webClientImgDownloader.OpenReadAsync(new Uri(dataItem.SourceUri,
UriKind.Absolute));
webClientImgDownloader.AddObject(dataItem); //????????????????????
webClientImgDownloader.Headers["idCode"] = dataItem.IdCode; //?????????????
webClientImgDownloader.ResponseHeaders["idCode"] = dataItem.IdCode; //?????????????
}
}
else
{
OnLoadingComplete(this, null);
}
}
Then when the loading of that image has completed, I save the image in a collection:
void webClientImgDownloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
dataItemIdCode = e.DataItem.IdCode; //???????????????????
dataitemIdCode = ((DataItem)sender).IdCode; //?????????????????????
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(e.Result);
Image image = new Image();
image.Source = bitmap;
Images.Add(dataItemIdCode, image);
}
But how do I pass the IdCode of the current DataItem through to my OpenReadCompleted method so that when that image has completed loading, I can also IDENTIFY it according to its IdCode?
Franci's suggestion works, here are the lines for anyone else looking for this::
webClientImgDownloader.OpenReadAsync(new Uri(dataItem.SourceUri,
UriKind.Absolute), dataItem);
...
DataItem dataItem = e.UserState as DataItem;
There's an OpenDataAsync overload that takes a user token object. You should get this object in the OpenReadCompletedEventArgs, in the UserState property (inherited from AsyncCompletedEventArgs).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With