任何人都有一个解释为什么下面的样式应用于绑定到2000个项目的集合的Silverlight ListBox在滚动列表时会像疯了一样泄漏内存?内存使用量很快就会达到数百兆字节。
只有在我离开ItemsControl时才会发生泄漏。否则内存消耗会保持不变。如果有问题的ItemsControl绑定的“Tags”属性(Type:string [])从其getter返回静态只读数组,则不会发生泄漏。
这是“Tags”属性getter的实现,我试图在循环中调用列表项的getter也会泄漏,但事实并非如此。我们说的是每个集合项目1-5个标签=最多10000个字符串。如果ItemsControl绑定到非静态集合,则看起来好像只发生泄漏。
运行时版本是4.0.60310.0,其AFAIK高于应该修复DataTemplate MemoryLeak的版本。
<Style x:Key="DocumentHybridListBox" TargetType="ListBox">
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Padding" Value="3"/>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<VirtualizingStackPanel VirtualizingStackPanel.VirtualizationMode="Recycling" Orientation="Vertical" Margin="1, 3, 1, 3" />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Style="{StaticResource DocumentList_Hybrid_Image}">
<Image.Source>
<BitmapImage Behaviors:BindableBitmapImageSource.Source="{Binding PreviewPicture}"></BitmapImage>
</Image.Source>
</Image>
<Grid Grid.Column="1" Margin="6, 0, 0, 0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="{Binding Summary}" FontWeight="Bold" TextTrimming="WordEllipsis"></TextBlock>
<TextBlock Grid.Row="2" Text="{Binding DateSummary}" FontSize="11" TextTrimming="WordEllipsis"></TextBlock>
<!--- Problem starts here -->
<ItemsControl Grid.Row="1" ItemsSource="{Binding Tags}" Margin="0, 3, 0, 3">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"></StackPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding}" Style="{StaticResource TagButton}"
Command="{Binding DataContext.TagDrillDownCmd, ElementName=Self}"
CommandParameter="{Binding}"
ToolTipService.ToolTip="{Binding Converter={StaticResource tagTooltipConverter}}"></Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Grid>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
标签属性:
private string[] _tags = null;
static readonly string[] constTags = new [] { "foo", "bar "};
public string[] Tags
{
get
{
//return constTags; // this won't leak if bound to ItemsControl
if (_tags == null)
{
// initialize
if (Document.Tags != null && Document.Tags.Length != 0)
{
// initialize
_tags = Document.Tags.Select(t => Decrypt2String(t,
ServiceLocator.Get<IKeyContainer>().DerivedContentEncryptionKey)).ToArray();
}
}
return _tags;
}
set
{
_tags = value;
OnPropertyChanged(()=>Tags);
}
}