我编写了一个简单的代码来允许在我的数据网格上进行过滤,但我在代码中犯了一个错误。但它仍然按预期工作。
这是我所做的:
- 获取源项目(从数据库)
- 从中创建
ICollectionView
- 设置我的自定义过滤器
- 将源绑定(bind)到DataGrid而不是 View
第四点是我犯错误的地方。我应该将 View 绑定(bind)到DataGrid,而不是源,对吧?
这是代码:
var mySources = GettingMySource();
var myView = CollectionViewSource.GetDefaultView(mySources);
myView.Filter = MyFilter;
DataGrid.ItemsSource = mySources;
在我的代码的其他地方(当用户输入过滤器时),我只需调用:
myView.Refresh();
它有效...与我的过滤器不匹配的元素将从 CollectionView 和 UI 中删除,但我的源列表保持不变...
有人可以解释一下这是如何工作的吗?
最佳答案
MSDN说:
All collections have a default CollectionView. WPF always binds to a view rather than a collection. If you bind directly to a collection, WPF actually binds to the default view for that collection. This default view is shared by all bindings to the collection, which causes all direct bindings to the collection to share the sort, filter, group, and current item characteristics of the one default view.
因此,当您告诉 DataGrid 使用源时,它仍然会自动采用在所有绑定(bind)上共享的(默认) View ,并应用您的过滤器。
编辑:
它还说
This default view is never affiliated with any CollectionViewSource objects.
因此,如果您将过滤器应用到 new CollectionViewSource(mySources)
的 View
而不是默认 View ,则不会进行过滤。
关于c# - WPF 绑定(bind)错误但 CollectionView 仍在过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41280866/