本文介绍了WPF基于画布的ItemsControl回收的物品最少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以Canvas为后盾PanelItemsControl.我经常需要.Clear()ObservableCollection是ItemsControl的ItemSource,然后向其中添加新信息,这将导致所有控件被销毁并创建新的UserControl,这非常缓慢.在我调用.Clear()之后,如何强制ItemsControl保留一定数量的容器,然后在将新项目添加到ItemSource时重用它们?

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?

推荐答案

我不确定这在您的用例中有多有效,但是您可以创建派生的ItemsControl并覆盖GetContainerForItemOverrideClearContainerForItemOverride方法以从缓存集合中放入和取出项目容器.

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

这篇关于WPF基于画布的ItemsControl回收的物品最少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 08:58