wpf - 使用 MVVM,每个 UI 窗口是否都有自己的 ViewModel?

标签 wpf design-patterns mvvm

当我在 MVVM 模式下设计多个 View 时,每个 View 是否都有自己的 ViewModel 还是它们都共享同一个?我知道这最终是一个灵活的决定,但最佳做法是什么?

我的直觉告诉我每个 View (即每个单独的 UI 窗口)都有一个 ViewModel。 MVVM 的所有博客示例都显示单一 View ,但仅此而已。

最佳答案

是的,基本上这个想法是你的 viewModel 应该只被一个 View 使用。如果您使用 viewModel 来填充一个区域(如在 ASP.NET MVC 中),则每次在不同位置呈现该 View 时都会“重用”该 viewModel。

article是 Josh Smith 对 MVVM 模式的讨论。然后,Ward Bell 在此讨论 article他认为 Josh 遗漏了什么,同时坚持认为 Josh 的工作仍然非常强大。

Ward 出色地阐述了这种模式的复杂性并展示了存在的紧张局势。以下是他对紧张局势的看法:

In my experience there is a “dialog” between View and ViewModel design. The VM exists to serve a view even as it strives for independence from any particular concrete view. A VM is useless if there is no view that will work with it; clearly the VM developer must heed the imprecations of the View developer.

On the other hand, in business applications the application’s imperatives – what the view must do to satisfy business requirements – are the province of the programmer and are > best articulated through the capabilities of the ViewModel.

Therein lies the necessary tension between View and ViewModel design. As a developer my allegiance is with the ViewModel (“the application should do something worthwhile”) but it would be silly to defend that allegiance at the expense of the View (“a good UX is essential to making an application easy to learn and to use”).

关于wpf - 使用 MVVM,每个 UI 窗口是否都有自己的 ViewModel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2790230/

相关文章:

design-patterns - 策略模式和委托(delegate)模式的区别

c# - 如何从 View 模型中显示自定义窗口,它们都位于单独的程序集中?

c# - 通过在MVVM中更改的属性来更改另一个类的属性?

c# - WPF - 如何访问 App.xaml.cs 中声明的方法?

wpf - 使用 Style 稍微修改控件模板

Iphone 游戏开发 - 需要设计指导

wpf - 将 UIElement 传递给 CommandParameter

c# - Visual Studio 2010 Crystal 报告 wpf

wpf - wpf mvvm datagrid选定的行

C# 类库 - 单例设计模式