由于某些烦人的原因,WPF 中的标记解析器会打开图像并保持与物理文件的连接处于打开状态。我在允许用户切换图像时遇到了类似的问题。我解决它的方法是使用IValueConverter
加载Image
并将 设置BitmapImage.CacheOption
为BitmapCacheOption.OnLoad
。尝试这个:
public class FilePathToImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value.GetType() != typeof(string) || targetType != typeof(ImageSource)) return false;
string filePath = value as string;
if (filePath.IsNullOrEmpty() || !File.Exists(filePath)) return DependencyProperty.UnsetValue;
BitmapImage image = new BitmapImage();
try
{
using (FileStream stream = File.OpenRead(filePath))
{
image.BeginInit();
image.StreamSource = stream;
image.CacheOption = BitmapCacheOption.OnLoad;
image.EndInit();
}
}
catch { return DependencyProperty.UnsetValue; }
return image;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
你可以像这样使用它:
<Application.Resources>
<Converters:FilePathToImageConverter x:Key="FilePathToImageConverter" />
</Application.Resources>
...
<Image Source="{Binding SomeObject.SomeImageFilePath,
Converter={StaticResource FilePathToImageConverter}, Mode=OneWay}" />