Silverlight Image binding Issue
I am trying to bind web address of an image (BigImageURL) with a image control. It works fine mostly but for some images i am getting http 403 error (found out using fiddler) and obviously the image does not get displayed. I want to display a static image in case the http url is not resolved.
<Image x:Name="HoverImage" Source="{Binding BigIma开发者_Python百科geURL}" />
I tried to write a converter
public class UriToImageSourceConverter : IValueConverter
{
public object Convert(object value, Type targetType,object parameter, CultureInfo culture)
{
BitmapImage image = null;
try
{
image = new BitmapImage(new Uri(value.ToString()));
}
catch (Exception ex)
{
image= new BitmapImage(new Uri("..<mydefaultimageUrl>.."));
}
return image;
}
...
}
<Image x:Name="HoverImage" Source="{Binding BigImageURL,Converter={StaticResource myUriToImageSourceConverter}" />
didn't work !! Even though the image url was not accessible, the converter didn't throw any exception. I don't think it tries to resolve the address or read image stream while creating the BitmapImage
Tried setting up a FallbackValue but it didn't work either.
<Image x:Name="HoverImage" Source="{Binding BigImageURL,FallbackValue=DefaultUrl}"/>
Any pointers ??
Thanks in advance
Actually you have to do something like this
<Image x:Name="HoverImage" Source="{Binding BigImageURL}"
ImageFailed="HoverImage_ImageFailed" />
and add event handler
private void HoverImage_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
var expection = e.ErrorException; // Here we could know what happend
HoverImage.Source = someDefaultUrl; // And here we add default Url...
}
In silverligth you have to handle not loader image and image exceptions with help of events... do not use databinding for that case..
精彩评论