How can I display a default image when the binded 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.
How can I display a default image when the binded 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.
I don' use wpf, so i don't know if there exists such a special feature.
But i would implement such a thing in the getter method of DisplayedBook.ImagePath
. It checks if the file exists and if not return a path to some default image.
You can probably do something like this:
Get the path of the image in path.
if (!File.Exists(path))
{
BitmapImage image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(path);
image.DecodePixelWidth = Convert.ToInt32(img.Width);
image.EndInit();
//Set the image corresponding to that bound
this.img.Source = image;
}
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 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}}" />
You can also add the FallbackValue
property which Gets or sets the value to use when the binding is unable to return a value.