过滤的CollectionView提供错误的计数

时间:2011-04-11 15:35:34

标签: wpf collectionview

根据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中有错误吗?我做错了什么,我看不到?

3 个答案:

答案 0 :(得分:5)

尝试

ICollectionView _cvs = CollectionViewSource.GetDefaultView(testList);

而不是

CollectionView testView = new CollectionView(testList);    

答案 1 :(得分: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";
}

答案 2 :(得分:0)

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

如果在添加项目之前设置过滤器,它将非常有用。或者您必须致电刷新。