So, I have a ListBox which is bound to a list of business objects, using a DataTemplate:
<DataTemplate x:Key="msgListTemplate">
<Grid Height="17">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{Binding MaxWidth}" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Foreground="Silver" Text="{Binding SequenceNo}" />
<TextBlock Grid.Column="1" Text="{Binding MessageName}" />
</Grid>
</DataTemplate>
<ListBox Name="msgList"
Grid.Column="0"
ItemTemplate="{StaticResource msgListTemplate}"
SelectionChanged="msgList_SelectionChanged"
VirtualizingStackPanel.IsVirtualizing="True"
ScrollViewer.HorizontalScrollBarVisibility="Hidden">
</ListBox>
Sometime after binding, I want to colour certain items in the list to distinguish them from the others. I do this on a background thread:
if(someCondition)
{
msgList.Dispatcher.BeginInvoke(new Fader(FadeListItem), DispatcherPriority.Render, request);
}
delegate void Fader(GMIRequest request);
void FadeListItem(GMIRequest request)
{
ListBoxItem item =
msgList.ItemContainerGenerator.ContainerFromItem(request) as ListBoxItem;
if(item!=null)
item.Foreground = new SolidColorBrush(Colors.Silver);
}
This all works fine, and some list items are greyed out as expected. However, if I scroll such that the greyed items are no longer shown, then scroll back again to where they were, they are no longer silver, and have returned to the default black foreground.
Any idea why this is, or how to fix it? Is it because I have set IsVirtualizing to true? The listbox typically contains many items (20,000 is not uncommon).