我应该绑定到 ICollectionView 还是 ObservableCollection [英] Should I bind to ICollectionView or ObservableCollection

查看:25
本文介绍了我应该绑定到 ICollectionView 还是 ObservableCollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否应该将 DataGrid 绑定到

ICollectionView = CollectionViewSource.GetDefaultView(collection)

或到

ObservableCollection;集合; ???

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);

在这种情况下,绑定到 collectioncollectionView 是一回事:绑定引擎将绑定到默认集合视图(引用等于 collectionView) 如果你告诉它绑定到 collection.

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.

这篇关于我应该绑定到 ICollectionView 还是 ObservableCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆