[英]Out of Memory Exception when Populating ListView with Images (Windows Phone 8.1)
因此,我可以將圖片庫中自定義文件夾中的圖像顯示到應用程序中的ListView中。 但是,當該自定義文件夾包含3張或更多圖片時,要么發生內存不足異常,要么應用崩潰,而Visual Studio甚至沒有意識到應用崩潰了。 我的問題是我該如何進行這項工作?
這是我的代碼...
在xaml.cs文件中:
List<StorageFile> FileList = (await temp.GetFilesAsync()).ToList();
List<ImageItem> ImageList = new List<ImageItem>();
for (int i = 0; i < FileList.Count; i++)
{
using (IRandomAccessStream FileStream = await FileList[i].OpenAsync(FileAccessMode.Read))
{
using(StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(ThumbnailMode.PicturesView))
{
if (thumbnail != null && thumbnail.Type == ThumbnailType.Image)
{
BitmapImage bitmap = new BitmapImage();
await bitmap.SetSourceAsync(FileStream);
ImageList.Add(new ImageItem() { ImageData = bitmap });
}
}
}
}
this.PhotoListView.DataContext = ImageList;
這是我的助手類 :
public class ImageItem
{
public BitmapImage ImageData { get; set; }
}
這是我的xaml ListView代碼:
<ListView Grid.Column="1"
Grid.Row="0"
x:Name="PhotoListView"
Grid.RowSpan="1"
ItemsSource="{Binding}">
<ListView.ItemTemplate>
<DataTemplate>
<Image Source="{Binding ImageData}"
Margin="10"/>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
</ListView>
代碼的問題在於,當您使用BitmapImage
,沒有指定DecodePixelHeight
和DecodePixelWidth
,可以通過兩種方法解決該問題:第一種是指定DecodePixelHeight
和DecodePixelWidth
,第二種是傳遞圖像的路徑使用以下代碼進入列表視圖:
List<StorageFile> FileList = (await temp.GetFilesAsync()).ToList();
List<string> ImageList = new List<string>();
foreach(var file in FileList)
{
ImageList.Add(file.Path);
}
this.PhotoListView.DataContext = ImageList;
Image控件能夠為您完成所有工作,並且還負責內存管理。
我覺得你的問題主要是設置ItemsPanelTemplate
到Stackpanel
。 這扼殺了虛擬化。 您沒有理由要覆蓋默認項目面板。
同樣如frenk91所述,將DecodePixelHeight
和DecodePixelWidth
添加到XAML中可能會很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.