I need to be able to use WebClient in a partiular way, I need to download an image as a Byte Stream and assign this to an Image, there are multiple images and items to be assigned, and these will appear in a list. This application is a Silverlight 3 application, solution must be one that works in Silverlight.
I have a Download Method I wish to use:
Public Sub Download(ByRef Source As Uri, ByRef Target As BitmapImage)
Dim _Client As New WebClient
_Client.OpenReadAsync(Source, Target)
AddHandler _Client.OpenReadCompleted, AddressOf Downloaded
End Sub
Here is the Downloaded Event Handler (Partial Implementation), which uses a ToByteArray Method to convert the downloaded image data to an array of Bytes.
Private Sub Downloaded(ByVal sender As Object, _
ByVal e As OpenReadCompletedEventArgs)
If Not e.Cancelled Then
Dim Bytes As Byte() = ToByteArray(e.Result)
Dim Bitmap As New BitmapImage
Bitmap.SetSource(e.Result)
' Set Target Bitmap Here
End If
End Sub
The Target Image to be set to the Downloaded Image (Target) is passed in as a UserToken to the OpenReadAsync Method, and can be read using the OpenReadCompletedEventArgs UserState Property, however this is ReadOnly – I need to set the Target to the Downloaded Image, inside the Downloaded Method.
How can the Image Source / Bitmap Image passed in as the UserToken in the Download Method be set in the Downloaded Method?
I’d re-arrange this code like this:-
Note calling this would be:-
The source of the returned bitmap will be set once the download is complete.
The
ToByteArraydidn’t appear to serve any purpose so I’ve removed it. I’ve also removed the ByRef passing.