Currently I’m working in a WPF project using prism 6, avoiding code-behind as much as possible. I have a variable in the ViewModel which contains the local path where the image in question is stored. In the View, I bind the source property of the Image control to the ViewModel’s variable and I can get the image displayed.
The problem arises when I need to delete the image from disk when it’s still being displayed in the view. Then, if I do so, I get the typical “Image is in use”. I read in the forum about image caching and I wonder if I could apply it in this case to avoid this behavior only using XAML if possible.
I’m using this approach:
<Border Grid.Column="0" BorderThickness="2" BorderBrush="#808080" Height="300"
Width="300" Background="#FCFCFC">
<Image Height="350" Width="350" HorizontalAlignment="Center"
VerticalAlignment="Center" Source="{Binding ImageUri}"/>
</Border>
You don't need to create an
ImageSource
object in yourViewModel
. Instead, just make a property of typebyte[]
, which you set from the file using standard IO functions. You can then bind theSource
property of yourImage
control to this byte array - the control will automatically handle the conversion to a displayable image.See my answer to this question for means to handle this in an async manner.
Once the file has been read, you can delete it as required. If the image comes from some external source, e.g. a web download, you can use the data directly without even needing to save it to disk at all.