tags:

views:

173

answers:

1

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>
+2  A: 

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

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.EndInit(); // load the image from the stream
            } // close the stream
            return image;
        }
    }
}
Thomas Levesque
Added this and it worked. Thanks!image.CacheOption = BitmapCacheOption.OnLoad;
James Cadd