2012-02-22 4 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을 retemplate하면 ​​데이터 가상화가 손실됩니다. 그래서, 모든 아이템 이미지는 항상 메모리에 있습니다. 높은 메모리 소비를 피하기 위해 이미지의 크기를 줄일 수 있습니까?

+0

오. 내 ListBox에 이미지가 있어야합니다. ListBox를 retemplate하고 데이터 가상화를 잃지 않는 방법을 알려주시겠습니까? – BillyMadisonnn

+0

당신이 할 수있는 방법 중 하나 : "더 많은"버튼을 삭제하고 다음 항목을로드하기 위해 하단 압축 상태를 감지하십시오 – Ku6opr

+0

솔루션 사용자 인 Scrollviewer와 itemsControl을 사용하여 ListBox를 구성하십시오 – BillyMadisonnn

0

가상화를 사용하려면 ListBox ControlTemplate을 변경해야한다고 생각합니다. ScrollViewer에서 ItemsPresenter를 제외한 모든 항목 이동 :

<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

+0

ScrollViewer에서 ItemsPresenter를 제외한 모든 항목을 이동합니다. 가상화는 여전히 비활성화되어 있습니다. 이런 경우에는 아마도 ListBox에 대한 기본 ControlTemplate을 사용하고 ListBox 근처에 '추가'버튼을 놓을 가치가 있습니다. – BillyMadisonnn

+0

이 문제를 게시 해 주셔서 감사합니다. 이러한 제한 사항을 알고 있어야합니다. 나는 전에 그것에 대해 읽은 적이 없다. – notacat

관련 문제