1

我需要能够以特定方式使用 WebClient,我需要将图像作为字节流下载并将其分配给图像,要分配多个图像和项目,这些将出现在列表中。此应用程序是 Silverlight 3 应用程序,解决方案必须是在 Silverlight 中工作的解决方案。

我有一个我想使用的下载方法:

    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

这是Downloaded Event Handler(部分实现),它使用ToByteArray方法将下载的图像数据转换为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

要设置为下载图像(目标)的目标图像作为 UserToken 传递给 OpenReadAsync 方法,并且可以使用 OpenReadCompletedEventArgs UserState 属性读取,但是这是只读的 - 我需要将目标设置为下载图像,在下载的方法中。

下载方法中作为UserToken传入的Image Source / Bitmap Image如何在Downloaded Method中设置?

4

1 回答 1

0

我会像这样重新安排这段代码:-

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   

注意调用这将是: -

myBitmap = Download(myUri)

下载完成后将设置返回位图的来源。

ToByteArray似乎没有任何用途,因此我将其删除。我还删除了 ByRef 传递。

于 2009-10-17T12:50:58.833 回答