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 Metho开发者_运维问答d, 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:-
Public Function Download(ByVal Source As Uri) As BitmapImage
Dim client As New WebClient
Dim target As BitMapImage
client.OpenReadAsync(Source, target)
AddHandler client.OpenReadCompleted, AddressOf Downloaded
Return target
End Sub
Private Sub Downloaded(ByVal sender As Object, _
ByVal e As OpenReadCompletedEventArgs)
If Not e.Cancelled Then
DirectCast(e.UserState, BitmapImage).SetSource(e.Result)
End If
End Sub
Note calling this would be:-
myBitmap = Download(myUri)
The source of the returned bitmap will be set once the download is complete.
The ToByteArray
didn't appear to serve any purpose so I've removed it. I've also removed the ByRef passing.
精彩评论