【问题标题】:ItemsControl in WPF generate all items even if Virtualization is enabled即使启用了虚拟化,WPF 中的 ItemsControl 也会生成所有项目
【发布时间】:2015-09-03 05:15:40
【问题描述】:

我有一个继承自 ItemsControl 的类和一个继承自 VirtualizedStack Panel 的 VirtualizedPanel,我创建了模板,以便我的控件将 Itemspresenter 保存在 ScrollViewer 中,并启用所有虚拟化属性以及 CanContentScroll。

问题是我在后端使用 DataVirtualization,所以我没有在内存和 WPF 中的所有集合,当 ItemsControl 被加载时,它调用 GetEnumerator(),所以它试图遍历集合.在 Silverlight 中,这不会发生,ItemsControl 只是使用实现 IList 的集合的索引器调用可见项。

有没有办法让 WPF 中的 ItemsControl 只使用索引器,而不是尝试通过 IEnumerable 加载所有集合?

【问题讨论】:

  • 你有没有在这里:bea.stollnitz.com/blog/?p=344?或多或少 2 年前,我正在使用 WPF,并使用了这篇文章中的一些技术,这非常好。

标签: c# wpf silverlight


【解决方案1】:

在 WPF 中默认情况下,虚拟化仅应用于 ListBox 和 ListView....尝试使用这些控件之一...

【讨论】:

  • 我遇到了使用 itemsControl,因为 ListBox 选择不能很好地与 Data Virtualized Collection 一起使用,滚动时会感到困惑,因为 Data 是 Virtualized,它无法通过比较来保持选择项目。
  • 在 WPF 中必须从 ListView 继承,它仍然会尝试使用 IEnumerable 但只要求第一项。我必须创建 #define 以便在 SL 上它从 ItemsControl 继承(自己处理选择,然后在 WPF 中它从 ListView 继承并让 ListView 处理选择。
【解决方案2】:

我在尝试为我的控件实现自定义集合时遇到了同样的问题,该集合继承自 ItemsControl。我的集合只实现了 IList,当我把它放在 ItemsSource 中时,除了索引器之外,只调用了 GetEnumerator 方法。当我从 IList 添加继承时,它开始调用索引器。

使用示例:

class MyClass : IList<T>, IList
{
  ...
        object IList.this[int index]
        {
            get { return this[index]; }
            set { throw new NotSupportedException(); }
        }

        public int this[int index]
        {
            get { return items[i]; }
            set { throw new NotSupportedException(); }
        }

        public IEnumerator<T> GetEnumerator()
        {
            for (int i = 0; i < count; i++)
            {
                yield return items[i];
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
  ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多