Noted: Universal Windows Platform (aka Windows 10 App, not WPF)
I have about 80 image files that need to be displayed on a listview inside a page. When user go back to previous page, i need to dispose the Image control so I can delete these images.
The problem is binding directly to image uri lock the image files, and it's not released when going back
I'm using MVVMLight
Some code:
public class FileNameToFullUriConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
string ori = value.ToString();
string file = ori.Split('/').Last();
string img = file.Split('.')[0] + ".png";
img = "ms-appdata:///local/" + StaticClass.ImageFolder + "/" + img;
return img;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return null;
}
}
and XAML
<DataTemplate>
<Grid>
<Image x:Name="Image2"
Grid.Column="1"
HorizontalAlignment="Left"
Source="{Binding Page2.Page.file,
Converter={StaticResource FileNameToFullUriConverter},
Mode=OneWay}"
Stretch="UniformToFill" />
</Grid>
</DataTemplate>
I've tried:
Set the list to null
Clear the list (by calling ListViewName.Clear() )
Call Cleanup in ViewModelLocator
What's working, but cannot apply: In ViewModel, I added another property with type of
ObservableCollection<BitmapImage>
, then binding the ListView to this collection. By using this way, all the image will be loaded into RAM, no lock on file, but it's cause a serious problem: Consume too much RAM. My app from using binding with URI took about 100 MB RAM to 900 MB RAM by binding directly to BitmapImage. Also, the time it took to load into the page take longer, since it has to read and load all the image file into RAM before the list finish rendered.
So, how to dispose Image Control in Windows 10?
PS: this image control: Image Class in MSDN
You can maintain a list of your Image controls in the code behind of the page. When the app go back, you can set Source property to null for each images :
<DataTemplate>
<Grid>
<Image Loaded="Image_Loaded" />
</Grid>
</DataTemplate>
In code behind :
private List<Image> _images = new List<Image>();
private void Image_Loaded(object sender, RoutedEventArgs e)
{
_images.Add(sender as Image);
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
foreach(var img in _images)
{
img.Source = null;
}
}
All locks will be released.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With