title: WPF item container recycling
body: <p>I want to implement a custom <code>Canvas</code> that recycles containers when used as an <code>ItemsPanel</code>. So I derived from <code>VirtualizingPanel</code> and override the <code>ArrangeOverride</code> and <code>MeasureOverride</code>. I am doing the generation in <code>MeasureOverride</code> like this:</p>
  
  <pre><code>var children = base.InternalChildren;
  
  var itemsControl = ItemsControl.GetItemsOwner(this);
  var itemsCount = itemsControl.Items.Count;
  
  IItemContainerGenerator generator = itemsControl.ItemContainerGenerator;
  
  var startPos = generator.GeneratorPositionFromIndex(0);
  
  using (generator.StartAt(startPos, GeneratorDirection.Forward, true))
  {
      for (int i = 0; i &lt; itemsCount; i++)
      {
          bool isNewlyRealized;
  
          var child = generator.GenerateNext(out isNewlyRealized) as UIElement;
  
          if (isNewlyRealized)
          {
              base.AddInternalChild(child);
              generator.PrepareItemContainer(child);
          }
  
          child.Measure(constraint);
      }
  }
  </code></pre>
  
  <p>What I don't know is how to make the recycling. I tried something like the following:</p>
  
  <pre><code>protected override void OnItemsChanged(object sender, ItemsChangedEventArgs e)
  {
      switch (e.Action)
      {
          case NotifyCollectionChangedAction.Remove:
          case NotifyCollectionChangedAction.Replace:
          case NotifyCollectionChangedAction.Move:
              IRecyclingItemContainerGenerator generator = ItemsControl.GetItemsOwner(this).ItemContainerGenerator;
              generator.Recycle(e.Position, e.ItemUICount);
              RemoveInternalChildRange(e.Position.Index, e.ItemUICount);
              break;
      }
  }
  </code></pre>
  
  <p>But it doesn't work. Any idea how to do this?</p>