I have a ListView-Control in XAML:
<ListView x:Name="conversationContent" Grid.Column="2" Margin="20,0,0,20" FontFamily="Global User Interface" >
<ListView.Resources>
<CollectionViewSource x:Name="conversationContentSource" IsSourceGrouped="False" />
<DataTemplate x:Key="DataTemplate1">
<Grid HorizontalAlignment="Stretch">
<Border x:Name="messageBorder" BorderBrush="Black" BorderThickness="1" Margin="0" CornerRadius="2" VerticalAlignment="Center" HorizontalAlignment="{Binding MTY, Converter={StaticResource messageAlignment}}" Child="{Binding MSG, Converter={StaticResource messageToRTF}}" />
</Grid>
</DataTemplate>
</ListView.Resources>
<ListView.ItemsSource>
<Binding Mode="OneWay" Source="{StaticResource conversationContentSource}"/>
</ListView.ItemsSource>
</ListView>
The CollectionViewSource is being set to some ObservableCollection<Message> at runtime from code behind.
Every Item in the ObservableCollection is being parsed by a Converter, it translates the complete Message (incl. BB-Codes) to a single RichTextBlock-Element, which contains other UI-Elements.
Sometimes, the CollectionViewSource.Source-Property changes to another ObersableCollection<Message>. When this happens, the ListView-Control builds up the new ItemList and displays it. As far as good.
The Problem is, the old Items are not going to be removed from Memory. Running the GC manually doesn’t change anything here.
I tried to iterate through the old items and delete them before changing the Source.
for (int ix = conversationContent.Items.Count - 1; ix >= 0; ix--) {
Debug.WriteLine("Type: " + conversationContent.Items.ElementAt(ix));
if (conversationContent.Items.ElementAt(ix) is RichTextBlock) {
conversationContent.Items.RemoveAt(ix);
}
}
But instead of RichTextBlock-Controls, there are only Objects of the type “Message”. Why?
I need to say, some of the generated Elements can contain Canvas-Elements with an update-function, which is being called every 200ms by a timer-event. Can this event-Binding prevent the GC to kill this objects?
I need a way to free up the memory, when the controls are not longer in use.
You can and should use a
RichTextBlockas yourItemTemplate. Research attached behaviors or attached dependency properties to figure out how to add a property to theRichTextBlockthat will convert your BB-code formatted message toRichTextBlockcontent. You can see an example that adds hyperlinked text to aRichTextBlockin WinRT XAML Toolkit here.For investigating memory leaks check this question: How to debug memory leaks in Windows Store apps?
Most frequent cause of memory leaks I see are event handlers that are never removed – make sure to remove all handlers on your
RichTextBlock‘sUnloadedevent. Also check if disabling all of your animations (e.g. in your animated emoticons).