0

我正在将 URI 绑定到图像,并且绑定工作得很好。问题是图像是动态生成的,并且生成可能会引发异常。我正在使用转换器,但似乎无法正确附加到 DecodeFailed 事件,或者我还缺少其他东西。这是我的代码:

Public Function Convert(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
        Dim image As New System.Windows.Media.Imaging.BitmapImage()
        Try
            image = New System.Windows.Media.Imaging.BitmapImage(New Uri(CStr(value)))
            AddHandler image.DownloadFailed, AddressOf DecodeFailed
            AddHandler image.DecodeFailed, AddressOf DecodeFailed
        Catch
            Return Windows.DependencyProperty.UnsetValue
        End Try
        Return image
    End Function

    Private Sub DecodeFailed(ByVal sender As Object, ByVal e As System.Windows.Media.ExceptionEventArgs)
        Dim image As System.Windows.Media.Imaging.BitmapImage = DirectCast(sender, System.Windows.Media.Imaging.BitmapImage)
        image.UriSource = New Uri("C:\Users\myUser\Desktop\errorSign.jpg")
    End Sub

当我从下载处理程序抛出异常时,DecodeFailed 或 DownloadFailed 都不会触发。Coverter 肯定在使用中,并且正在显示图像。

...
<myNs:ImageConverter x:Key="ImageConverter"></myNs:ImageConverter>
...
<Image Height="125" Source="{Binding Path=Uri, Converter={StaticResource ImageConverter}}"/>
4

1 回答 1

0

弄清楚了:

Public Shared Event DownloadOrDecodeFailed(ByVal oldUri As String, ByVal newUri As String)
Public Function Convert(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
            Dim image As New System.Windows.Media.Imaging.BitmapImage()
            Try
                AddHandler image.DownloadFailed, AddressOf OnDownloadOrDecodeFailed
                AddHandler image.DecodeFailed, AddressOf OnDownloadOrDecodeFailed
                image.BeginInit()
                image.UriSource = DirectCast(value, Uri)
                image.EndInit()
            Catch
                Return Windows.DependencyProperty.UnsetValue
            End Try
            Return image
        End Function

        Private Shared Sub OnDownloadOrDecodeFailed(ByVal sender As Object, ByVal e As System.Windows.Media.ExceptionEventArgs)
            Dim image As System.Windows.Media.Imaging.BitmapImage = DirectCast(sender, System.Windows.Media.Imaging.BitmapImage)
            RaiseEvent DownloadOrDecodeFailed(image.UriSource.AbsolutePath, "C:\Users\myUser\Desktop\errorSign.jpg")
        End Sub

因为事件是共享的,如果引发事件的图像源相同,我可以附加到它并从视图模型更新图像 uri。

于 2011-11-03T22:17:59.253 回答