【问题标题】:Filtered CollectionView Gives Wrong Count过滤的 CollectionView 给出错误的计数
【发布时间】:2011-08-03 04:24:21
【问题描述】:

根据documentation,过滤后的 CollectionView 的 Count 应该只是通过过滤器的项目的计数。鉴于此代码:

List<string> testList = new List<string>();
testList.Add("One");
testList.Add("Two");
testList.Add("Three");
testList.Add("1-One");
testList.Add("1-Two");
testList.Add("1-Three");
CollectionView testView = new CollectionView(testList);
int testCount1 = testView.Count;
testView.Filter = (i) => i.ToString().StartsWith("1-");
int testCount2 = testView.Count;

因此,我希望 testCount1 为 6,而 testCount2 为 3。但是,两者都是 6。如果我手动遍历 CollectionView 并计算项目,我确实得到 3,但 Count 总是返回 6。

我尝试在 CollectionView 上调用 Refresh,只是想看看这是否会纠正结果,但没有任何变化。文档有错吗? CollectionView 中是否有错误?我是不是做错了什么我看不到的事情?

【问题讨论】:

  • 这必须有效,但我不确定:testview.OfType().Count()

标签: wpf collectionview


【解决方案1】:

似乎有一个错误,如果您尝试调用“刷新”,我检查了反射器可能会为您提供正确的计数。根据文档,他们说您不需要调用 Refresh,因为设置过滤器会自动刷新它,但我认为这不会发生,因为他们还提到他们缓存了上次更改的计数值。

如果您在添加项目之前设置过滤器,它会很完美。否则您将不得不调用 Refresh。

【讨论】:

  • 我尝试将其更改为调用 Refresh(),但这并没有改变任何内容。
【解决方案2】:

试试

ICollectionView _cvs = CollectionViewSource.GetDefaultView(testList);

而不是

CollectionView testView = new CollectionView(testList);    

【讨论】:

  • 实际上,即使上面的解决方案在您的情况下返回了正确数量的结果,如果您在过滤后检查您的集合视图的“原始结果”,也只有 3 个项目被考虑在内属性仍然是 à 6...
  • +1,使用CollectionViewSource.GetDefaultView是正确的方法。
  • CollectionViewSource.GetDefaultView 所做的只是创建一个 ListCollectionView 并将其缓存在内部地图中。此外,这为您提供了一个用于基本集合的全局 CollectionView,这是我绝对不想要的 - 我肯定想获得一个本地实例。
【解决方案3】:

如果你切换到 ListCollectionView,那么它会按预期工作:

CollectionView testView = new ListCollectionView(testList);
int testCount1 = testView.Count;
testView.Filter = (i) => i.ToString().StartsWith("1-");
int testCount2 = testView.Count;

这似乎适用于 CollectionView,所以这肯定指向一个错误:

CollectionView testView = new CollectionView(this.GetTestStrings());

private IEnumerable<string> GetTestStrings() {
    yield return "One";
    yield return "Two";
    yield return "Three";
    yield return "1-One";
    yield return "1-Two";
    yield return "1-Three";
}

【讨论】:

  • +1,另外,CollectionViewSource.GetDefaultView 将确保检索到正确的CollectionView
  • @sixlettervariables - 是的,这就是为什么我赞成布鲁诺的回答 ;-)
  • 但是,如果我的源列表没有实现 IList(例如,如果我有一个 Collection),那么我不能使用 ListCollectionView,我必须使用基本的 CollectionView。
  • @David - 实际上,如果您通过 ICollection,那么它会按预期工作。看来 CollectionView 不能很好地处理 IList。
  • @David - 抱歉,我的意思是 IEnumerable。
猜你喜欢
  • 2015-07-12
  • 2019-12-06
  • 2017-01-07
  • 1970-01-01
  • 1970-01-01
  • 2018-12-26
  • 1970-01-01
  • 2016-01-14
  • 1970-01-01
相关资源
最近更新 更多