C# 使用图像填充ListView时出现内存不足异常(Windows Phone 8.1)
因此,我可以将图片库中的自定义文件夹中的图像显示到应用程序中的列表视图中。但是,当该自定义文件夹包含3个或更多图像时,要么出现内存不足异常,要么应用程序崩溃,Visual Studio甚至没有意识到应用程序已经崩溃。我的问题是,我如何才能使这项工作 这是我的密码 在xaml.cs文件中:C# 使用图像填充ListView时出现内存不足异常(Windows Phone 8.1),c#,xaml,windows-phone-8.1,out-of-memory,C#,Xaml,Windows Phone 8.1,Out Of Memory,因此,我可以将图片库中的自定义文件夹中的图像显示到应用程序中的列表视图中。但是,当该自定义文件夹包含3个或更多图像时,要么出现内存不足异常,要么应用程序崩溃,Visual Studio甚至没有意识到应用程序已经崩溃。我的问题是,我如何才能使这项工作 这是我的密码 在xaml.cs文件中: List<StorageFile> FileList = (await temp.GetFilesAsync()).ToList(); List<ImageItem> ImageLis
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;
这是我的xaml列表视图代码:
<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;
List FileList=(wait temp.getfileasync()).ToList();
List ImageList=新列表();
foreach(文件列表中的var文件)
{
Add(file.Path);
}
this.PhotoListView.DataContext=ImageList;
图像控件可以为您完成所有工作,并负责内存管理。我认为您的主要问题是将
ItemsPanelTemplate
设置为Stackpanel
。这扼杀了虚拟化。您没有理由覆盖默认项目面板
同样正如frenk91所提到的,在XAML中添加
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;