I have a LongListSelector which contains a image control which loads a lot of images from the web, this works fine for some time, but after i loaded some images i get out of
I know no way to prevent the LongListSelector from leaking memory. However, you can use a small trick to free the memory used by pictures.
First, create a new class, called SafePicture
, and make it inherit from ContentControl
. Inside, implement the logic to free the memory used by the bitmap:
public class SafePicture : System.Windows.Controls.ContentControl
{
public SafePicture()
{
this.Unloaded += this.SafePictureUnloaded;
}
private void SafePictureUnloaded(object sender, System.Windows.RoutedEventArgs e)
{
var image = this.Content as System.Windows.Controls.Image;
if (image != null)
{
image.Source = null;
}
}
}
Then, wrap all your pictures using this custom control:
<phone:Pivot Title="MY APPLICATION">
<!--Pivot item one-->
<phone:PivotItem Header="Browse">
<Grid>
<phone:LongListSelector Name="llsGameList" ItemsSource="{Binding}" Tap="llsGameList_Tap" Margin="0,90,0,0">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<Grid>
<my:SafePicture>
<Image Name="imgGameList" Margin="0,10,0,10" Stretch="Fill" HorizontalAlignment="Left" VerticalAlignment="Top" Height="200" Width="150">
<Image.Source>
<BitmapImage UriSource="{Binding BoxArtFrontThumb}"
CreateOptions="BackgroundCreation" DecodePixelHeight="200" DecodePixelWidth="150" />
</Image.Source>
</Image>
</my:SafePicture>
</Grid>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</Grid>
</phone:PivotItem>
Note that the namespace my
refers to the assembly you've put the SafePicture
in, and must be declared on top of your page:
xmlns:my="clr-namespace:yourNamespace"