我正在 WPF 中开发一个图像管理应用程序,它显示许多图像并允许用户在文件系统中移动它们。我遇到的问题是显示带有<Image>
元素似乎使文件保持打开状态,因此尝试移动或删除文件会失败。有没有办法手动要求 WPF 卸载或释放文件以便可以移动它?或者是否有一种显示图像的方法不保持文件打开?下面的查看器 Xaml:
<ListBox x:Name="uxImages" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Border Margin="4">
<Image Source="{Binding}" Width="150" Height="150"/>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
是什么ItemsSource
你的ListBox
?包含图像路径的字符串列表?
不要隐式使用从字符串到 ImageSource 的内置转换器,而是使用自定义转换器在加载图像后关闭流:
public class PathToImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string path = value as string;
if (path != null)
{
BitmapImage image = new BitmapImage();
using (FileStream stream = File.OpenRead(path))
{
image.BeginInit();
image.StreamSource = stream;
image.CacheOption = BitmapCacheOption.OnLoad;
image.EndInit(); // load the image from the stream
} // close the stream
return image;
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)