我有这样的 XAMl
<Image x:Name="MyImage">
<Image.Source>
<BitmapImage UriSource="{Binding FullPhotoPath}" CacheOption="OnLoad" />
</Image.Source>
</Image>
Run Code Online (Sandbox Code Playgroud)
只要 FullPhotoPath 存在,这就可以正常工作。如果没有,那么它会抛出异常
“System.Windows.Media.Imaging.BitmapImage”的初始化引发异常。
我意识到我可以只使用图像标签
要显示图像,如果它不存在,则不会显示任何内容(并且不会引发异常),但据我所知,此语法不允许我使用CacheOption.
如果图像路径不存在,如何不显示任何内容?
您可以使用转换器使用所需的任何设置来创建 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();
}
}
Run Code Online (Sandbox Code Playgroud)
使转换器可以在某处访问
<local:PathToBitmapImagelConverter x:Key="PathToBitmapImagelConverter"/>
Run Code Online (Sandbox Code Playgroud)
然后在您的 XAML 中使用,例如
<Image x:Name="MyImage" Source="{Binding FullPhotoPath, Converter={StaticResource PathToBitmapImagelConverter}}"/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4116 次 |
| 最近记录: |