C# 图像源绑定到丢失的文件

C# 图像源绑定到丢失的文件,c#,wpf,image,data-binding,C#,Wpf,Image,Data Binding,当绑定路径文件丢失时,如何显示默认图像 <Image Source="{Binding DisplayedBook.ImagePath}" /> 我的解决方案:使用转换器,它检查图像是否存在并返回适当的路径。我不使用wpf,所以我不知道是否存在这样的特殊功能 但是我会在DisplayedBook.ImagePath的getter方法中实现这样的事情。它检查文件是否存在,如果不存在,则返回某个默认图像的路径。您可能可以执行以下操作: 获取路径中图像的路径 if (!File.

当绑定路径文件丢失时,如何显示默认图像

<Image  Source="{Binding DisplayedBook.ImagePath}" />



我的解决方案:使用转换器,它检查图像是否存在并返回适当的路径。

我不使用wpf,所以我不知道是否存在这样的特殊功能


但是我会在
DisplayedBook.ImagePath
的getter方法中实现这样的事情。它检查文件是否存在,如果不存在,则返回某个默认图像的路径。

您可能可以执行以下操作:

获取路径中图像的路径

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

如果您有与此XAML关联的代码隐藏(即不是模板),则可以在ImageFailed事件上设置默认映像:

<Image  Source="{Binding ImagePath}" ImageFailed="Image_ImageFailed" />

如果您不想从
ImagePath
getter返回默认图像,那么另一种方法是返回null

public string ImagePath
{
   get
   {
     return File.Exists(m_Path) ? m_Path : null;
   }
}
在XAML中,使用绑定的TargetNullValue属性

<Image  Source="{Binding DisplayedBook.ImagePath, TargetNullValue={StaticResource SomeImageResource}}" />


您还可以添加
FallbackValue
属性,该属性获取或设置绑定无法返回值时要使用的值

我想了想,问题是它将书本实体与UI结合起来。书也不知道默认图像是什么。
<Image  Source="{Binding DisplayedBook.ImagePath, TargetNullValue={StaticResource SomeImageResource}}" />