wpf - MVVM 中的大型模型集合

标签 wpf mvvm

在 WPF 中实现我的第一个 MVVM 应用程序时,我一直想知道将模型集合包装在相关的 ViewModel 集合中以便在 View 中使用的利弊。

在我们的系统中,我们可能有几个潜在的大型集合,例如订单中的订单行,以及可以为订单行选择的库存项目。目前这些是从数据访问层的 SQL 中查找的,然后循环 SqlDataReaders 以创建模型对象的集合。

然后在创建 ViewModel 对象集合时循环 Model 对象集合似乎是不必要的开销。当存在大量 Model 对象集合时,直接在 View 上公开这些对象会更好吗?

预先感谢您的帮助,马克


编辑 在阅读这个主题时,我发现 this MSDN article从今年 7 月开始(由 Josh Smith 审阅)给出了 MVVM 的相当平衡的观点,并且在“集合”部分中这样说:

Another problem with collections is determining when or if to wrap each Model instance in the collection within a ViewModel instance. For smaller collections, the ViewModel may expose a new observable collection and copy everything in the underlying Model collection into the ViewModel observable collection, wrapping each Model item in the collection in a corresponding ViewModel instance as it goes. The ViewModel might need to listen for collection-changed events to transmit user changes back to the underlying Model.

However, for very large collections that will be exposed in some form of virtualizing panel, the easiest and most pragmatic approach is just to expose the Model objects directly.

非常感谢到目前为止的评论,尝试限制传递到 ViewModel 的数据量,或者使用分页或其他合适的控件会减少问题,我敢肯定,但我想知道是否还会有这样的情况简单地绑定(bind)到 ViewModel 中的 Model 对象集合会更好吗?

最佳答案

我想这实际上取决于您想如何显示数据。毕竟 ViewModel 主要用于处理 View 所需的数据。

假设您的数据层只为您提供数据集合,您始终可以根据您实际想要查看的元素来限制 ViewModel 中元素的创建。

例如,您可能有一个数据网格来显示给定订单的订单项。

因此您可以将 ViewModel 属性 AllOrderItems 绑定(bind)到数据网格,但它的 getter 如下所示:

public List<OrderItems> AllOrderItems
{
get{return this.DataAccessLayer.GetOrderItems().Where(x=>x.OrderNumber==this.OrderNumber).toList();
}

这里的 DataAccessLayer 是一个保存缓存数据库数据和数据库接口(interface)的类。如果保持为单例,则将减少其中的数据重复。

您可以调整您的 ViewModel 以根据需要从 DataAccessLayer 过滤尽可能多或尽可能少的数据。如果需要,集合可以是可观察的,并且 DataAccessLayer 可以为 VM 生成事件以对添加、删除、保存到数据库的新数据的情况使用react。

关于wpf - MVVM 中的大型模型集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3813740/

相关文章:

c# - 此命名空间冲突是由于 XAML 到 .NET 代码生成中的错误造成的吗?

wpf - 如何在滚动查看器中获得滚动条以在单击时聚焦滚动查看器?

javascript - 在 MV* 设计模式中,模型是单个数据单元还是与数据一起工作的所有逻辑?

wpf - MVVM 中的绑定(bind) slider 值

wpf - 实体/业务对象验证的建议,其中验证依赖于其他实体/服务

wpf - 卡特尔延迟加载包含 View / View 模型的装配体

c# - 在多列中显示 ComboBoxItems

c# - 如何以编程方式添加更多样式 setter ?当我尝试时,出现 InvalidOperationException 异常(SetterBaseCollection 正在使用中)

wpf - 在 WPF 中使用复杂的 Winforms 控件(如 ZedGraph)和 MVVM 设计

silverlight - 刷新WP7中的列表框