【问题标题】:Out of Memory Exception when Populating ListView with Images (Windows Phone 8.1)使用图像填充 ListView 时出现内存不足异常 (Windows Phone 8.1)
【发布时间】:2016-03-23 12:25:51
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    您的代码的问题是,当您使用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 控件能够为您完成所有工作,并且还负责内存管理。

    【讨论】:

    • 谢谢!这解决了我的问题。我想我可能只是把事情复杂化了,所以我编辑了我的代码,现在它可以完美运行了。
    【解决方案2】:

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

    正如 frenk91 所提到的,将 DecodePixelHeightDecodePixelWidth 添加到您的 XAML 中可能会有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-18
      • 2015-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多