使用图像填充ListView时出现内存不足(Windows Phone 8.1)

时间:2016-03-23 12:25:52

标签: c# xaml windows-phone-8.1 out-of-memory

因此,我可以将图片库中自定义文件夹中的图像显示到应用程序中的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>

2 个答案:

答案 0 :(得分:3)

您的代码存在的问题是,当您使用BitmapImage而未指定DecodePixelHeightDecodePixelWidth时,您可以通过两种方式解决问题: 第一个是指定DecodePixelHeightDecodePixelWidth,第二个是使用以下代码将图像的路径传递到列表视图:

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控件能够为您完成所有工作,并负责内存管理。

答案 1 :(得分:2)

我认为您的主要问题是将ItemsPanelTemplate设置为Stackpanel。这会杀死虚拟化。您没有理由覆盖默认项目面板。

同样如frenk91所述,将DecodePixelHeightDecodePixelWidth添加到您的XAML可能会有用。