title: Custom VirtualizingPanel: IItemContainerGenerator.IndexFromGeneratorPosition(position) returns -1
body: <p>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 </p>
  
  <pre><code>IItemContainerGenerator.IndexFromGeneratorPosition(position) 
  </code></pre>
  
  <p>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.</p>
  
  <p>The problem arises when a NullReferenceException occurs when i execute the IItemContainerGenerator.Remove(position, offset) method.</p>
  
  <p>The code below shows the method where i virtualize the items</p>
  
  <pre><code>private void CleanupItems()
  {
      IItemContainerGenerator iGenerator = this.ItemsOwner.ItemContainerGenerator;
  
      for (int i = this.InternalChildren.Count - 1; i &gt;= 0; i--)
      {
  
          GeneratorPosition position = new GeneratorPosition(i, 0);
          int itemIndex = iGenerator.IndexFromGeneratorPosition(position);
  
          if (itemIndex &lt; this.StartIndex || itemIndex &gt; this.EndIndex)
          {
              iGenerator.Remove(position, 1);
              this.RemoveInternalChildRange(i, 1);
          }
  
      }
  }
  </code></pre>
  
  <p>currently i put this(fix?hack?) in my VirtualizingPanel's constructor</p>
  
  <pre><code>Loaded += (s, e) =&gt;
  {
      if (ItemsOwner.ItemsSource != null)
      {
          this.InvalidateMeasure();
      }
  };
  </code></pre>
  
  <p>how should i fix this issue the correct way? any suggestions?</p>