据斯特凡威克的博客绑定的数据,从图像释放内存仅仅是因为这样做简单:清除图像缓存(释放内存)时,图像在XAML
BitmapImage bitmapImage = image.Source as BitmapImage;
bitmapImage.UriSource = null;
image.Source = null;
但是,我怎么能达到同样的效果如果我使用的数据在XAML绑定这样?:
// inside MainPage.xaml
<Button Tap="GetImages">Get Images</Button>
<ListBox ItemSource="{Binding Links}">
<ListBox.ItemTemplate>
<DataTemplate>
<!-- I am not binding to Image's Source directly, because I want to use the bitmap's 'Background creation' option and it's download progress event in the future -->
<Image>
<Image.Source>
<BitmapImage UriSource="{Binding}" CreateOptions="BackgroundCreation"/>
</Image.Source>
</Image>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
//inside MainPage.xaml.cs
public void GetImages(object sender, RoutedEventArgs e) {
(DataContext as ViewModel).GetMeSomeImages();
}
// inside ViewModel.cs
public void GetMeSomeImages() {
List<string> links = ThisMethodGetsLinks();
Links.Clear();
foreach(var link in links)
Links.Add(link);
}
ObservableCollection<string> _links;
public ObservableCollection<string> Links {
get {
if (_links == null)
_links = new ObservableCollection<string>();
return _links;
}
}
在这种情况下,每个按钮自来水将占用更多的内存,直到手机/仿真器崩溃。即使Listbox的ItemSource属性被清除,图像也不会从内存中释放。
你是如何试图释放列表框中图像的内存的? – 2012-02-28 00:38:51
好吧,目前在我的应用程序中,我绑定了一个像这样的图像,其中MyImage是一个BitmapImage,我创建并存储在视图模型中的可观察集合中,但我需要手动启动后台线程并通过Webclient下载。然后,一旦我请求新的图像,我'清除'Listbox的ItemSource被设置为的ObservableCollection(通过将每个MyImage的UriSource设置为null)似乎可以保持内存不变,但它比Xaml解决方案更加冗长。我一直在扫描互联网寻找基于Xaml的解决方案,但没有运气。 –
krdx
2012-02-28 01:02:04