How can I display a default image when the bound path file is missing?
<Image Source="{Binding DisplayedBook.ImagePath}" />
My solution: Used a converter, which check if the image exists and returns the appropriate path.
if you don't want to return default image from ImagePath getter, than another approach is to return null.
public string ImagePath
{
get
{
return File.Exists(m_Path) ? m_Path : null;
}
}
and in XAML use TargetNullValue property of Binding
<Image Source="{Binding DisplayedBook.ImagePath, TargetNullValue={StaticResource SomeImageResource}}" />
If you have code-behind associated with this XAML (i.e. not a Template) you can set a default image on the ImageFailed event:
<Image Source="{Binding ImagePath}" ImageFailed="Image_ImageFailed" />
and the handler:
private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
Image image = e.Source as Image;
if (image != null)
image.Source = new BitmapImage(new Uri("http://SomeDefaultImagePath.jpg"));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With