gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:43:52 24 4
gpt4 key购买 nike

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

这是我做的:

  1. 获取源项目(从数据库)
  2. 从中创建 ICollectionView
  3. 设置我的自定义过滤器
  4. 绑定(bind)到DataGrid而不是 View

第四点是我犯的错误。我应该将 view 绑定(bind)到 DataGrid,而不是 source,对吗?

代码如下:

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 使用源时,它仍然会自动采用(默认) View ,该 View 在所有绑定(bind)上共享并应用了您的过滤器。

编辑:

还说

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com