I'm using an ItemsControl
with a Canvas
as its backing Panel
. I often need to .Clear() the ObservableCollection
is the ItemsControl's ItemSource
, and then add new information to it, which causes all the controls to be destroyed and new UserControl
s to be created, which is very sluggish. How can I force the ItemsControl to retain a certain amount of containers even after I call .Clear(), and then reuse them when new items are added to the ItemSource?
I am not sure how efficient this would be in your use case, but you might create a derived ItemsControl and override the GetContainerForItemOverride
and ClearContainerForItemOverride
methods to put and take item containers from a cache collection.
public class CachingItemsControl : ItemsControl
{
private readonly Stack<DependencyObject> itemContainers =
new Stack<DependencyObject>();
protected override DependencyObject GetContainerForItemOverride()
{
return itemContainers.Count > 0
? itemContainers.Pop()
: base.GetContainerForItemOverride();
}
protected override void ClearContainerForItemOverride(
DependencyObject element, object item)
{
itemContainers.Push(element);
}
}