gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 10:13:13 25 4
gpt4 key购买 nike

当我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com