S
S
Slavka2017-01-25 22:57:55
WPF
Slavka, 2017-01-25 22:57:55

How is the relationship between ViewModel and Model done in MVVM?

Не могу понять одну вещь в паттерне mvvm, как должна узнавать viewmodel об изменеиях в model, к примеру у меня модель постоянно получает в фоне какое нибудь данные, и я хочу их видеть в gui, для этого мне пришлось делать открытым свойсвом observablecollection в модели и подписываться на его изменения, чтоб изменить коллекцию в ViewModel, возможно я не доконца понимаю связь этих двух сущностей.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stanislav Makarov, 2017-01-26
@Nipheris

In general, the way notifications are passed from the model to the ViewModel is not regulated by the MVVM pattern. How best to do this depends on your task.
Perhaps the ViewModel itself will know when and in what case which properties of the model are changed and will itself generate the necessary PropertyChanged events.
Perhaps the model will have task-specific events (for example, the model will call PlayerMoveCompleted when the player makes a move), which the ViewModel will subscribe to and will, in turn, generate the necessary PropertyChanged.
Некоторые советуют в модели также реализовать INotifyPropertyChanged, но лично мне этот способ не нравится: во-первых, в модель начинает подмешиваться UI, что обычно нехорошо, а во-вторых - нотификация о смене значений конкретных пропертей это всё-таки задача ViewModel, и я не вижу смысла размазывать её ещё и на модель. Последняя должна содержать только специфичные для предметной области вещи.

Антон Папин, 2017-01-25
@i_light

A model in MVVM should not contain any data. The data is needed to display in the View, respectively, they are obtained and used in the ViewModel.
Model is a model of some entity (usually a database table) and should consist mainly of data manipulation methods.
For example:
UserModel - methods for creating, deleting, editing and getting one or a list of users.
UserViewModel - storing a list of users, or storing user field data, commands for obtaining data from the model, including here there may be autonomous ones (for example, by a timer).

E
eugene73, 2017-02-24
@eugene73

Делайте опрос датчиков во ViewModel, методы вычислений пускай будут в Model, их нужно вызывать из ViewModel.
Ну, или если вы настаиваете на своей схеме, когда вся работа по получению и обработке данных выполняется в Model, используйте Catel. В Catel.MVVM есть атрибуты свойств [Model] и [ViewModelToModel], которые позволяют связать свойства Model и ViewModel.
Или самостоятельно реализуйте INotifyPropertyChanged в модели.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question