Should one bind DataGrid to the

ICollectionView = CollectionViewSource.GetDefaultView(collection)

or to the

ObservableCollection<T> collection; ???

What is the best practice for MVVM and why?

推荐答案

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

Assume that we have

var collection = new ObservableCollection<string>();
var collectionView = CollectionViewSource.GetDefaultView(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.

This means that the answer to your question is "it makes absolutely no difference".

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.

.net相关问答推荐

删除数据库项目中的表

如何使用 awslocal 通过 localstack 中的 cloudwatch events/eventbridge 触发 lambda

仅在有换行符时捕获分隔符之间的所有文本

为什么 .NET 中的 System.Version 定义为 Major.Minor.Build.Revision?

在 C# 中生成随机小数

.NET 4.0 中有内置的二叉搜索树吗?

[DllImport("QCall")] 是什么?

使用 .NET 中的代码更改桌面墙纸

InternalsVisibleTo 属性不起作用

Java 和 .NET 技术/框架的类似物

日期时间是什么意思?在 C# 中是什么意思?

Await 运算符只能在 Async 方法中使用

如何防止任务的同步延续?

log4net的正确使用方法(记录器命名)

使用 DateTime.ToString() 时获取日期后缀

根据条件从列表中删除项目

/langversion 的错误选项6无效;必须是 ISO-1、ISO-2、3、4、5 或默认值

Linq Query 不断抛出无法创建 System.Object 类型的常量值......,为什么?

嵌套捕获组如何在正则表达式中编号?

泛型类的静态成员是否与特定实例相关联?