【问题标题】:Custom VirtualizingPanel: IItemContainerGenerator.IndexFromGeneratorPosition(position) returns -1自定义 VirtualizingPanel:IItemContainerGenerator.IndexFromGeneratorPosition(position) 返回 -1
【发布时间】:2013-09-15 16:54:11
【问题描述】:

我正在构建一个自定义 VirtualizingPanel 以用于 ListBox 控件。 我正在做一些测试,我在方法中遇到了问题

IItemContainerGenerator.IndexFromGeneratorPosition(position) 

如果我在承载 ListBox 的 UserControl 的构造函数(在 Loaded 事件之前)中设置 ListBox 的 ItemsSource,它将返回 -1。但是,如果我在 Loaded 事件中设置 ListBox 的 ItemsSource,它不会返回 -1。

当我执行 IItemContainerGenerator.Remove(position, offset) 方法时发生 NullReferenceException 时,就会出现问题。

下面的代码显示了我虚拟化项目的方法

private void CleanupItems()
{
    IItemContainerGenerator iGenerator = this.ItemsOwner.ItemContainerGenerator;

    for (int i = this.InternalChildren.Count - 1; i >= 0; i--)
    {

        GeneratorPosition position = new GeneratorPosition(i, 0);
        int itemIndex = iGenerator.IndexFromGeneratorPosition(position);

        if (itemIndex < this.StartIndex || itemIndex > this.EndIndex)
        {
            iGenerator.Remove(position, 1);
            this.RemoveInternalChildRange(i, 1);
        }

    }
}

目前我把这个(修复?hack?)放在我的 VirtualizingPanel 的构造函数中

Loaded += (s, e) =>
{
    if (ItemsOwner.ItemsSource != null)
    {
        this.InvalidateMeasure();
    }
};

我应该如何以正确的方式解决这个问题?有什么建议吗?

【问题讨论】:

    标签: c# wpf custom-controls virtualization custom-panel


    【解决方案1】:

    IItemContainerGenerator.IndexFromGeneratorPosition 将返回 -1,以防您的项目没有生成容器。

    在构造函数时,您的项目不会在 UI 上呈现。因此没有容器,但一旦你的 UI 被渲染,它们就可用。这就是您在加载事件后获取它们的原因。

    您可以检查您的 ItemContainerGenerator 的状态,在处理您的请求之前它应该是ContainersGenerated。挂钩StatusChanged 事件

    ItemsOwner.ItemContainerGenerator.StatusChanged += (s, args) =>
    {
        if (ItemsOwner.ItemContainerGenerator.Status == 
                           GeneratorStatus.ContainersGenerated)
        {
            // Your code goes here.         
        }
    };
    

    【讨论】:

    • 感谢回复,您介意解释一下 ItemContainerGenerator 的生命周期吗?
    • 链接在这里 - drwpf.com/blog/category/item-containers 将帮助您了解它是如何工作的。
    • 嗨,我仍然面临这个问题。实际上,当我执行上面的 CleanUpItems() 方法时,ItemContainerGenerator 的状态已经是 ContainersGenerated ...所以我认为您的回复无效
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-26
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多