I am trying to create a listbox containing an Image and some details of it. Here is the code:
<ListBox x:Name="GalleryImages" ItemsSource="{Binding}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel VirtualizingStackPanel.VirtualizationMode="Recycling" Orientation="Vertical" ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.VerticalScrollBarVisibility="Disabled" HorizontalAlignment="Center"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid VerticalAlignment="Top">
<Image Source="{Binding Path=ImageSrc}" Height="200" Width="480" Stretch="Fill"/>
<Border BorderThickness="5" BorderBrush="White" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="10" >
<StackPanel HorizontalAlignment="Center" Background="White" Opacity="0.6">
<TextBlock Text="{Binding Path=Time}" Foreground="Black" HorizontalAlignment="Center" Padding="10,5,10,0" FontSize="12" />
<TextBlock Text="{Binding Path=Day}" Foreground="Black" HorizontalAlignment="Center" FontSize="45" FontWeight="Bold" Padding="10,0,10,10" Margin="0,-10,0,-18"/>
<TextBlock Text="{Binding Path=MonthAndYear}" Foreground="Black" HorizontalAlignment="Center" FontSize="17" Padding="10,0,10,5"/>
</StackPanel>
</Border>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
the backened code is:
public class Item
{
public ImageSource ImageSrc { get; set; }
public string Time { get; set; }
public string Day { get; set; }
public string MonthAndYear { get; set; }
}
//Creating a New Item
//Added the time,day, monthandyear
//Now adding the image source
//This will be looped each time for each image
Item item = new Item();
using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
{
if (ISF.DirectoryExists("SomeDirectory"))
using (IsolatedStorageFileStream FS = ISF.OpenFile("SomeDirectory/" + "SOMERANDOMIMAGENAME", FileMode.Open, FileAccess.Read))
{
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(FS);
item.ImageSrc = bitmap;
}
}
At last binding the items to the listbox one-by-one created before:
Dispatcher.BeginInvoke(() => GalleryImages.Items.Add(item));
Now the problem is: As you can see that all the listbox images are being fetched from the Isolated Storage using a new Bitmap Image and then setting it to the item.ImageSrc. But when the items go beyond 25 it creates a Memory Leak and the app crashes after displaying the images
what i tried till now,
- added virtualizingstackpanel, which worked but, not for images beyond 25.
- set the item.ImageSrc = null just after adding the item to the GalleryImage(ListBox) Items, but that makes the images of the ListBox null too.
What else i can do to work this out, for images more than 1000??