开发者

Image Source bound to missing file

How can I display a defau开发者_StackOverflowlt 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"));
    }


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;
}


You can also add the FallbackValue property which Gets or sets the value to use when the binding is unable to return a value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜