[英]MVVM ViewModel-Model
Can I create an instance of the ViewModel
in the View
or it's inappropriate? 我可以创建的实例
ViewModel
的View
,或者它不合适? I would need it, because the Command
of a MenuFlyoutItem
dynamically changes depending on the content of the Button
(the Button
content depends on a Json
file). 我需要它,因为
MenuFlyoutItem
的Command
根据Button
的内容动态地改变( Button
内容取决于Json
文件)。
Usually there are two approaches for ViewModel
lifetime - singleton and tied to a specific instance of the view. 通常,
ViewModel
生命周期有两种方法 - 单例并绑定到视图的特定实例。 For global ViewModels
that are tied to a certain View
for the whole lifetime of the app you will create a singleton instance of the ViewModel
. 对于在应用程序的整个生命周期中绑定到某个
View
全局ViewModels
,您将创建ViewModel
的单例实例。 Example for this could be the ViewModel
of the root page of the app. 此示例可以是应用程序根页面的
ViewModel
。 This page will definitely appear only once in the navigation stack so you can safely use just one instance. 此页面肯定只会出现在导航堆栈中一次,因此您可以安全地只使用一个实例。 A problem appears when there is a way for the user to repeat one
View
multiple times in the navigation stack. 当用户有一种方法在导航堆栈中多次重复一个
View
时,会出现问题。 If you were using just one singleton instance of the ViewModel
, by navigating to the second instance of the View
you would essentially lose the the data tied to the previous instance and after navigating back you would see different data. 如果您只使用
ViewModel
一个单例实例,通过导航到View
的第二个实例,您将基本上丢失与前一个实例关联的数据,在导航回来之后,您将看到不同的数据。 Example would be a shopping app, where you have a product (A) and in the product view you have a list of related items. 示例是购物应用,您有产品(A),在产品视图中有相关项目列表。 If the user selected one of them (say product B), then in cas of singleton
ViewModel
the instance would be refreshed to contain data of product B and when going back you would have to manually change the data back to product A. By having multiple instances of one ViewModel
for each instance of the tied View
in the navigation stack you can avoid reloading the data, which could be costly in case they are acquired from a remote service, for example. 如果用户选择了其中一个(比如产品B),则在单个
ViewModel
的cas中,实例将被刷新以包含产品B的数据,并且当返回时,您将不得不手动将数据更改回产品A.例如,对于导航堆栈中绑定的View
每个实例,一个ViewModel
的实例可以避免重新加载数据,例如,如果从远程服务获取数据,这可能是昂贵的。 You can always manage all active ViewModels
in a global array and remove the references to the ones no longer needed, so they can be freed up from memory. 您始终可以管理全局数组中的所有活动
ViewModels
,并删除对不再需要的引用,以便可以从内存中释放它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.