简体   繁体   English

C#mvvm如何将模型传递给viewmodel

[英]c# mvvm how to pass model to viewmodel

I have read a lot about MVVM in the past, but I am not completely getting there. 过去,我已经阅读了很多有关MVVM的内容,但是我还没有完全了解。 I looked at MVVM Light framework and understood the pattern of the ServiceLocater to bind View and Viewmodel. 我查看了MVVM Light框架,并了解了ServiceLocater绑定View和Viewmodel的模式。 But I didnt find anything helpful about the connection between the model and the viewmodel. 但是我没有发现有关模型与视图模型之间连接的任何帮助。

So far I know that the Viewmodel should have a private "Model" instance and some public properties to be read by the View. 到目前为止,我知道Viewmodel应该具有一个私有的“ Model”实例和一些公共属性,以供View读取。 The Model should implement the INotifyPropertyChanged event to notify the Viewmodel, which can do something with the data and/or change its public properties and notify the view. 该模型应实现INotifyPropertyChanged事件以通知Viewmodel,后者可以对数据进行某些操作和/或更改其公共属性并通知视图。

I hope I got it right so far. 我希望到目前为止我做对了。 But: Where is the Model created? 但是:模型是在哪里创建的? and how does the Viewmodel gets the Model? 以及Viewmodel如何获取模型? Does the Viewmodel creates it? Viewmodel是否创建它? My Application gets data via bluetooth continously and process them in the background. 我的应用程序连续通过蓝牙获取数据并在后台处理它们。 At different process-stages it changes different Models. 在不同的流程阶段,它会更改不同的模型。 My first approach was a Singleton which holds all Models. 我的第一个方法是拥有所有模型的Singleton。 The Viewmodel gets the Model from the Singleton and the Background-process can access the Model too. Viewmodel从Singleton获取模型,并且后台进程也可以访问模型。 But I think that "pattern" is really bad.., but i cannot find any solution to do this "nice". 但是我认为“模式”确实很糟糕。.但是我找不到任何解决方案来做到这一点。 I dont know how to share the model between the viewmodel and the background-process (businessLogic) properly. 我不知道如何在viewmodel和后台进程(businessLogic)之间正确共享模型。

I am glad about any help :) 我很高兴有任何帮助:)

As far as I know and use to do in our WPF projects - classical MVVM delegates Model creation on ViewModel. 据我所知并在我们的WPF项目中经常使用-经典MVVM在ViewModel上委托模型创建。 ViewModel should be Model-aware. ViewModel应该是可识别模型的。 Sometimes ViewModel could rely on ServiceLocator or DependencyInjection patterns to find out and create Model class (ie by interface). 有时,ViewModel可以依赖ServiceLocator或DependencyInjection模式来发现并创建Model类(即通过接口)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM