您可以使用如下所示的绑定转换器,通过设置BitmapCacheOption.OnLoad将图像直接加载到内存缓存。该文件会立即加载,之后不会锁定。
<Image Source="{Binding ...,
Converter={StaticResource local:StringToImageConverter}}"/>
转换器:
public class StringToImageConverter : IValueConverter
{
public object Convert(
object value, Type targetType, object parameter, CultureInfo culture)
{
object result = null;
var path = value as string;
if (!string.IsNullOrEmpty(path))
{
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri(path);
image.EndInit();
result = image;
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
更好的是,直接从 FileStream 加载 BitmapImage:
public object Convert(
object value, Type targetType, object parameter, CultureInfo culture)
{
object result = null;
var path = value as string;
if (!string.IsNullOrEmpty(path) && File.Exists(path))
{
using (var stream = File.OpenRead(path))
{
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = stream;
image.EndInit();
result = image;
}
}
return result;
}