MVVM 模式中 View-first 与 ViewModel-first 的优缺点是什么 [英] What are the pros and cons of View-first vs. ViewModel-first in the MVVM pattern

查看:12
本文介绍了MVVM 模式中 View-first 与 ViewModel-first 的优缺点是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在演示如何在现实世界的应用程序中使用 MVVM,并且我将包含一个关于在您的应用程序中使用 MVVM 作为模式时涉及的 religious wars 设计决策的部分.在 MVVM 应用程序中,有两种主要方式(据我所知)来实例化新的 View/ViewModel 对:

I'm giving a presentation on using MVVM in real world applications and I'm including a section on the religious wars design decisions involved when using MVVM as a pattern in your application. In an MVVM application there are two main ways (that I know of) to instantiate a new View/ViewModel pair:

  1. View-First,您可以在其中创建一个视图,然后它会创建自己的 ViewModel 并将其设置为它的 DataContext.
  2. ViewModel-First,您可以在其中创建新视图模型并创建新视图以响应 ViewModel 属性的更改,通常使用 ItemsControls 和/或 DataTemplates.
  1. View-First in which you create a view and it creates its own ViewModel and sets it to its DataContext.
  2. ViewModel-First in which you create new view models and create new views in response to changes in ViewModel properties, usually with ItemsControls and/or DataTemplates.

根据您的经验,每种方法的优缺点是什么?它们有什么作用,你会遇到什么问题?

In your experience what are the pros and cons of each method? What do they enable and what problems do you run into with each?

  • 首先查看 - 优点
    • 易于跟踪视图使用了哪个视图模型
    • 不允许单个 View 与多个 ViewModel 轻松使用
    • 需要额外的事件来处理视图和视图模型之间的通信
    • 允许更完整的逻辑测试以打开新的视图和视图模型
    • 随着应用程序变大,趋向于 DRYer
    • View 和 ViewModel 更加独立,可以更轻松地单独处理
    • 在没有 DataTemplateSelector 和类型化 DataTemplate 的情况下,在 Silverlight 中设置更加困难.

    推荐答案

    鉴于 WPF 中的数据模板功能,我觉得 ViewModel-First 是 WPF 打算使用的方式.

    Given the Data Templating feature in WPF, I feel ViewModel-First is the way WPF was intended to be used.

    我将澄清该声明:数据模板允许您从不从 ViewModel 实例化视图.如果操作正确,您的视图和视图模型可以保存在不相互引用的单独项目中.此外,ViewModel 项目甚至不应引用任何 PresentationFramework 程序集,从而使您的 ViewModel 可供任何可能的用户使用.

    I'll clarify that statement: Data Templating allows you to never instantiate views from your ViewModel. If done correctly, your Views and ViewModels could be kept in seperate projects that DO NOT reference each other. Furthermore, the ViewModel project should not even reference any PresentationFramework assemblies, making your ViewModels consumable by any conceivable user.

    这篇关于MVVM 模式中 View-first 与 ViewModel-first 的优缺点是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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