0

我加载了大量图像,例如250+,并且出现了内存异常异常。在wp7中加载大量图像时出现内存不足异常

我的代码:

while (kount < imageItems.Count) 
{ 
    for (int i = 0; i < _grid.RowDefinitions.Count; i++) 
    { 
     BitmapImage bit=null; 
     for (int j = 0; j < _grid.ColumnDefinitions.Count; j++) 
     { 
      imgGrd = new Image(); 
      bit = new BitmapImage(new Uri(imageItems[kount].thumb_attachment, UriKind.RelativeOrAbsolute)); 
      imgGrd.Source = bit; 

      imgGrd.Stretch = Stretch.UniformToFill; 

      _grid.Children.Add(imgGrd); 
      Grid.SetRow(imgGrd, i); 
      Grid.SetColumn(imgGrd, j); 
      //bit = null; 
      //imgGrd.Source = null; 
      kount++; 
     }  
    } 
} 

如何克服这个问题。在此先感谢..

+0

增加内存的可能性吗?如果没有,则加载较少的图像或较小的图像文件... –

+0

如何在图像从其获取源时丢弃位图对象。 –

回答

0

您不应该一次创建所有图像。手机有办法为您创建和处理图像。这是通过使用一些内置的ItemsControl控件完成的。其中最受欢迎的是ListBox。为了让ListBox创建并处理这些项目,您需要创建一个DataTemplate来创建图像。

<ListBox ItemsSource="{Binding ImageItems}"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <Image Source="{Binding thumb_attachment}"/> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

而不是通过你的ImageItems循环和手动创建图像,你可以让手机来照顾这一点。这要求您创建一个对象来将您的页面绑定到具有ImageItems属性的页面。

public class MainViewModel // Should probably implement INotifyPropertyChanged 
{ 
    public IEnumerable<ImageItem> ImageItems { get; set; } 
} 

有了这个页面,它将DataContext设置为MainViewModel。

如果要显示网格中的项目,则可以将ListBox的ItemsPanelTemplate更改为Windows Phone Toolkit中的WrapPanel。

<ListBox.ItemsPanelTemplate> 
    <toolkit:WrapPanel /> 
</ListBox.ItemsPanelTemplate> 
相关问题