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

查看:322
本文介绍了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. 视图优先" ,您在其中创建视图,并创建自己的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?

  • 先查看-优点
    • 轻松跟踪视图使用哪个ViewModel
    • View First - Pros
      • Easy to track which ViewModel is used by a View
      • 不允许单个View轻松与多个ViewModels一起使用
      • 需要额外的事件来处理View和ViewModel之间的通信
      • 允许对逻辑进行更完整的测试,以打开新的Views和ViewModels
      • 随着应用程序的变大,它趋于变干
      • View和ViewModel更加独立,可以更轻松地分别进行处理
      • 如果没有DataTemplateSelector和键入的DataTemplates,在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实例化视图.如果正确完成,则您的Views和ViewModels可以保存在彼此不引用的单独项目中.此外,ViewModel项目甚至不应引用任何PresentationFramework程序集,从而使您的ViewModels可以由任何可能的用户使用.

      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天全站免登陆