c# - WPF 绑定(bind)错误但 CollectionView 仍在过滤

标签 c# wpf datagrid collectionviewsource

我编写了一个简单的代码来允许在我的数据网格上进行过滤,但我在代码中犯了一个错误。但它仍然按预期工作。

这是我所做的:

  1. 获取源项目(从数据库)
  2. 从中创建 ICollectionView
  3. 设置我的自定义过滤器
  4. 绑定(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/

相关文章:

c# - 从另一个窗体刷新Form1 dataGrid c# winform

c# - 如何过滤掉国家代码?

c# - 尝试使用 ManagedEsent 访问/附加 ESE 数据库时出现问题

c# - Nunit - 每次测试前执行的全局方法

c# - 如何保存 WPF UI 状态?

wpf - 如何将序列号添加到行标题

wpf - 有哪些好的 WPF Datagrid 使用示例?

c# - Post 方法获取空参数 ASP .NET MVC

c# - ComboBox - 自动完成 + 自由打字

WPF 工具包 DataGrid 多选 : How to get SelectedItems out?