Reputation: 35
this is my ListBox:
XMLA:
<Style x:Key="ListBoxStyle" TargetType="ListBox">
<Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBox">
<ScrollViewer x:Name="ScrollViewer">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="{TemplateBinding Height}"/>
<RowDefinition Height="100"/>
</Grid.RowDefinitions>
<ItemsPresenter Grid.Row="0"/>
<Button Content="Add" Grid.Row="1" Click="Button_Click"/>
</Grid>
</ScrollViewer>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style> <ListBox Style="{StaticResource ListBoxStyle}" Name="listBox" Height="600" ItemsSource="{Binding MyData}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}"/>
<Image Source="{Binding Img}" Stretch="UniformToFill"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Code-Behind:
private void Button_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 50; i++)
{
MyData.Add(new Data { Name = i.ToString(), Img = "/Background.png" });
}
}
When I Click Button more, I get a OutOfMemoryException.
but,If I don't set ListBox Style. I add Items into ListBox,the Project is Work.
Upvotes: 0
Views: 503
Reputation: 691
I suppose, to enable virtualization you should change ListBox ControlTemplate. Move all except of ItemsPresenter out of ScrollViewer:
<ControlTemplate TargetType="ListBox">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="100"/>
</Grid.RowDefinitions>
<ScrollViewer x:Name="ScrollViewer" Grid.Row="0">
<ItemsPresenter />
</ScrollViewer>
<Button Content="Add" Grid.Row="1" Click="Button_Click"/>
</Grid>
</ControlTemplate>
And make sure that your MyData implements IList interface.
Upvotes: 0
Reputation: 8126
When you retemplate the ListBox
, you lose data virtualization. So, all your item images are in memory all the time. Can you decrease the size of the images to avoid high memory consumption?
Upvotes: 1