I had an issue with using Images and provide a right-click context menu for deleting the Image.
Originally I was binding the absolute file path:
<Image Source="{Binding Path=ImageFileName} .../>
where ImageFileName
is something like C:\myapp\images\001.png
.
I was getting an error, The process cannot access the file 'X' because it is being used by another process
. After a lot of research, I figured out the necessary code change.
I used this Stackoverflow answer: Delete a file being used by another process and put the code into a ValueConverter
.
XAML:
<Image Source="{Binding Path=ImageFileName,
Converter={StaticResource pathToImageConverter}}" ...>
Value Converter:
public class PathToImageConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
try
{
String fileName = value as String;
if (fileName != null)
{
BitmapImage image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri(fileName);
image.EndInit();
return image;
}
return new BitmapImage();
}
catch
{
return new BitmapImage();
}
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
The concern I have is memory usage. When I add Images to my Container, I see memory increase. However, when I delete Images, and the underlying file is deleted, I do not see any memory being freed up.
I've also always thought of Bitmaps as a very inefficient file format, since they are uncompressed, and tend to be HUGE compared to a JPEG or PNG file. Is the
System.Windows.Media.Imaging.BitmapSource
class actually creating an uncompressed image out of my PNG?
Thanks very much in advance!
Philip