在WPF中显示图像而不保持文件打开 [英] Display an image in WPF without holding the file open

查看:113
本文介绍了在WPF中显示图像而不保持文件打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用WPF中的图像管理应用程序,该应用程序显示许多图像并允许用户在文件系统中移动它们。我遇到的问题是显示带有< Image> 元素的文件似乎保持文件打开,因此尝试移动或删除文件失败。有没有办法手动要求WPF卸载或释放文件,以便可以移动?或者是否有一种显示不保持文件打开的图像的方法?下面的查看器Xaml:

I'm working on an image management app in WPF that displays a number of images and allows the user to move them around the file system. The issue I've run into is that displaying a file with an <Image> element appears to hold the file open, so attempts to move or delete the file fail. Is there a way to manually ask WPF to unload or release a file so it can be moved? Or is there a method of displaying images that doesn't hold the file open? Viewer Xaml below:

<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 ?包含图像路径的字符串列表?

What is the ItemsSource of your ListBox ? A list of strings containing the image paths ?

在加载后,使用自定义转换器关闭流,而不是隐式使用从字符串到ImageSource的内置转换器image:

Instead of implicitly using the built-in converter from string to ImageSource, use a custom converter to close the stream after you load the image :

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;
        }
    }
}

这篇关于在WPF中显示图像而不保持文件打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆