你可以使用一个转换器与任何你需要的设置,这也可以只返回null,如果你看到的文件不存在,然后只绑定通过转换器的Image.Source创建的BitmapImage。
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}}"/>
你在代码隐藏文件试图处理异常? XAML不支持此功能 – uowzd01 2015-04-01 01:17:34