2012-02-22 65 views
0

這是我的列表框:當我添加多個項目到ListBox時,我得到OutOfMemoryException。如何修改它?

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風格。我將項目添加到列表框中,該項目是工作。

回答

1

當您重新模擬ListBox時,會丟失數據虛擬化。所以,你的所有物品圖像始終在內存中。你能減小圖像的大小以避免高內存消耗嗎?

+0

哦。我的列表框必須有圖像。你能告訴我如何重新模板我的列表框,而不會丟失數據虛擬化? – BillyMadisonnn 2012-02-22 11:32:01

+0

你可以這樣做的方法之一:刪除「更多」'按鈕'並檢測底部壓縮狀態以加載下一個項目 – Ku6opr 2012-02-22 11:35:14

+0

我找到了一個解決方案用戶Scrollviewer和itemsControl組成一個ListBox – BillyMadisonnn 2012-02-22 11:49:04

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接口。

+0

MyData實現IList接口。 – BillyMadisonnn 2012-02-22 12:04:39

+0

將ItemsPresenter的所有項目移出ScrollViewer。在這種情況下,虛擬化仍然是禁用的 – BillyMadisonnn 2012-02-22 12:06:41

+0

,可能值得使用ListBox的默認ControlTemplate並將「添加」按鈕放在ListBox附近。 感謝您發佈此問題,瞭解這些限制很重要。我從來沒有讀過這個。 – notacat 2012-02-22 12:52:45

相關問題