I am building a custom VirtualizingPanel to be used in and ListBox control. I am doing some testing where i faced a problem in the method
IItemContainerGenerator.IndexFromGeneratorPosition(position)
It returns -1 if I set the ListBox's ItemsSource in the constructor(which is before the Loaded event) of my UserControl where it hosts the ListBox. However, it does not returns -1 if I were to set the ListBox's ItemsSource in the Loaded event.
The problem arises when a NullReferenceException occurs when i execute the IItemContainerGenerator.Remove(position, offset) method.
The code below shows the method where i virtualize the items
private void CleanupItems()
{
IItemContainerGenerator iGenerator = this.ItemsOwner.ItemContainerGenerator;
for (int i = this.InternalChildren.Count - 1; i >= 0; i--)
{
GeneratorPosition position = new GeneratorPosition(i, 0);
int itemIndex = iGenerator.IndexFromGeneratorPosition(position);
if (itemIndex < this.StartIndex || itemIndex > this.EndIndex)
{
iGenerator.Remove(position, 1);
this.RemoveInternalChildRange(i, 1);
}
}
}
currently i put this(fix?hack?) in my VirtualizingPanel's constructor
Loaded += (s, e) =>
{
if (ItemsOwner.ItemsSource != null)
{
this.InvalidateMeasure();
}
};
how should i fix this issue the correct way? any suggestions?