WPF Canvas-based ItemsControl with minimum recycled items?

自作多情 提交于 2019-12-08 11:35:32

问题


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 UserControls 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?


回答1:


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);
    }
}


来源:https://stackoverflow.com/questions/22218506/wpf-canvas-based-itemscontrol-with-minimum-recycled-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!