Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image Source bound to missing file

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.

like image 805
Amirshk Avatar asked Aug 12 '26 23:08

Amirshk


2 Answers

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}}" />
like image 106
Yuriy Zanichkovskyy Avatar answered Aug 14 '26 16:08

Yuriy Zanichkovskyy


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"));
    }
like image 42
John Bowen Avatar answered Aug 14 '26 16:08

John Bowen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!