Bakri Bitar
Bakri Bitar

Reputation: 1697

WPF Changing image path and show the new image in Runtime

I have WPF Image, the source of it is local image URI on my Hard Disk, and I'm using converter to load it.

I want to alter the image on the hard disk ( replace it with another one ) and in runtime show the new image

Here the XAML of the image

 <Image  Stretch="Fill">
                                            <Image.Style>
                                                <Style TargetType="Image">
                                                    <Setter Property="Source" Value="{Binding ImagePath,Converter={StaticResource ImageFileLoader},UpdateSourceTrigger=PropertyChanged}"/>
                                                </Style>
                                            </Image.Style>
                                        </Image>

Here is the converter

 class ImageFileLoader : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value != null)
        {
            string filePath = value.ToString();
            if (File.Exists(filePath))
            {
                BitmapImage result = new BitmapImage();
                result.BeginInit();
                result.UriSource = new Uri(filePath);
                result.CacheOption = BitmapCacheOption.OnLoad;
                result.EndInit();
                return result;
            }

        }

        return null;
    }

}

Note : I tried to change the CacheOption in the converter to BitmapCacheOption.None or any other option ... it did't work because in this case I cannot alter the image on the Hard disk

Upvotes: 0

Views: 1462

Answers (1)

Sheridan
Sheridan

Reputation: 69979

When the Framework loads an Image, it puts an annoying hold on it, so that if you try to delete or move the actual image file, you'll get an Exception saying something like Cannot access the file because it is being used. To get around that, I created an IValueConverter like yours in order to set the Image.CacheOption to BitmapCacheOption.OnLoad which Caches the entire image into memory at load time, thereby removing the hold.

However, the code in my Converter looks similar to yours, so I'm not sure why it won't work for you. Here is what my IValueConverter code looks like:

using (FileStream stream = File.OpenRead(filePath))
{
    image.BeginInit();
    image.StreamSource = stream;
    image.CacheOption = BitmapCacheOption.OnLoad;
    image.EndInit();
}

Upvotes: 2

Related Questions