ListBox コントロールで使用するカスタム VirtualizingPanel を構築しています。メソッドで問題に直面した場所でいくつかのテストを行っています
IItemContainerGenerator.IndexFromGeneratorPosition(position)
ListBox をホストする UserControl のコンストラクター (Loaded イベントの前) に ListBox の ItemsSource を設定すると、-1 が返されます。ただし、Loaded イベントで ListBox の ItemsSource を設定した場合、-1 は返されません。
IItemContainerGenerator.Remove(position, offset) メソッドを実行したときに NullReferenceException が発生すると、問題が発生します。
以下のコードは、アイテムを仮想化する方法を示しています
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);
}
}
}
現在、私はこれ(修正?ハック?)をVirtualizingPanelのコンストラクターに入れています
Loaded += (s, e) =>
{
if (ItemsOwner.ItemsSource != null)
{
this.InvalidateMeasure();
}
};
この問題を正しい方法で修正するにはどうすればよいですか? 助言がありますか?