我正在努力将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}}"/>
答案 0 :(得分: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。