我应该绑定到的ICollectionView或的ObservableCollection绑定、ICollectionView、ObservableCollection

2023-09-02 10:30:13 作者:这世界真无趣

如果一项结合的DataGrid

的ICollectionView = CollectionViewSource.GetDefaultView(集合)

或到

的ObservableCollection< T>集合; ???

什么是MVVM和最佳实践,为什么?

What is the best practice for MVVM and why?

推荐答案

您的总是的绑定到一个的ICollectionView ,不管你让它明示或不是。

You always bind to an ICollectionView, whether you make it explicit or not.

假设我们有

var collection = new ObservableCollection<string>();
var collectionView = CollectionViewSource.GetDefaultView(collection);

在这种情况下,结合集合的CollectionView 是同一个:绑定引擎将绑定到默认集合视图(这是引用等于的CollectionView ),如果你告诉它绑定到集合

In this case, binding to collection or to collectionView is one and the same: the binding engine will bind to the default collection view (which is reference equal to collectionView) if you tell it to bind to collection.

这意味着,回答你的问题是它使绝对没有什么区别。

只是要完全清楚:即使你绑定到集合直接绑定引擎将绑定到默认视图。修改视图的属性,如排序标准将影响出现直接绑定到集合的结合,因为后面的盖子是有约束力的默认视图来代替。

Just to be totally clear: even if you bind to the collection directly, the binding engine will bind to the default view. Modifying properties of the view such as sort criteria will affect the binding that appears to bind directly to the collection, since behind the covers it's a binding to the default view instead.

然而,还有另外一个有趣的和相关的问题:人应该绑定到默认集合视图(即与集合本身,因为没有理由将其明确绑定到默认视图)或同一集合的另一个看法?

However, there is another interesting and related question: should one bind to the default collection view (i.e., to the collection itself, because there's no reason to explicitly bind to the default view) or to another view of the same collection?

考虑到每个视图都有自己的当前项目,排序标准等的概念,它遵循,如果你打算有多个绑定到相同的收集和绑定控件需要对当前项目,筛选不同的观念和公司,那么你想要的是明确地绑定到同一底层集合的多个视图。

Considering that each view has its own notion of current item, sort criteria, etc, it follows that if you intend to have multiple bindings to the same collection, and the bound controls need to have distinct notions of current item, filters and company, then what you want is to explicitly bind to multiple views of the same underlying collection.