这是我的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>
代码隐藏:
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" });
}
}
当我点击按钮时,我得到一个OutOfMemoryException。
但是,如果我没有设置ListBox样式。我将项目添加到ListBox中,Project is Work。
答案 0 :(得分:1)
重新尝试ListBox
时,会丢失数据虚拟化。因此,您的所有项目图像始终在内存中。您是否可以减小图像的大小以避免高内存消耗?
答案 1 :(得分:0)
我想,要启用虚拟化,您应该更改ListBox ControlTemplate。将除ItemsPresenter之外的所有内容移出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>
确保MyData实现IList接口。