当文件不存在时,BitmapImage会抛出初始化异常

时间:2015-03-31 23:41:32

标签: c# wpf

我有这样的XAMl

<Image x:Name="MyImage">
    <Image.Source>
        <BitmapImage UriSource="{Binding FullPhotoPath}"   CacheOption="OnLoad" />
    </Image.Source>
</Image>

只要FullPhotoPath存在,这样就可以正常工作。如果没有,则抛出

的例外
  

初始化&#39; System.Windows.Media.Imaging.BitmapImage&#39;抛出异常。

我意识到我只能使用Image标签

要显示图像,如果它不存在,则不会显示任何内容(并且不会抛出任何异常),但据我所知,此语法不允许我使用CacheOption

如果图像路径不存在,我该如何显示?

1 个答案:

答案 0 :(得分:2)

您可以使用转换器创建您需要的任何设置的BitmapImage,如果您发现该文件不存在,则只返回null,然后通过转换器绑定Image.Source。

public class PathToBitmapImagelConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string path = value as string;

        if (path == null || !File.Exists(path))
            return null;

        var bmp =  new BitmapImage();
        bmp.BeginInit();
        bmp.CacheOption = BitmapCacheOption.OnLoad;
        bmp.UriSource = new Uri(path, UriKind.RelativeOrAbsolute);
        bmp.EndInit();
        return bmp;
    }


    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

让转换器可以在某处访问

<local:PathToBitmapImagelConverter x:Key="PathToBitmapImagelConverter"/>

然后在你的XAML中使用

<Image x:Name="MyImage" Source="{Binding FullPhotoPath, Converter={StaticResource PathToBitmapImagelConverter}}"/>