10

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

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 中是否有错误?我做错了什么我看不到的事情吗?

4

3 回答 3

5

尝试

ICollectionView _cvs = CollectionViewSource.GetDefaultView(testList);

代替

CollectionView testView = new CollectionView(testList);    
于 2011-04-11T16:25:10.390 回答
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";
}
于 2011-04-11T16:25:28.500 回答
0

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

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

于 2011-04-11T16:15:40.170 回答