What is the best practice for accessing a model using the MVVM pattern

I have a database that communicates with webservices with my model (native thread) and provides data objects. My user interface application consists of different views and views and user controls. I use ServiceProvider (IServiceProvider) to access the Model and route events to the UI thread. The relationship between ViewModels is handled by Messenger.

Is it so?

I was also interested to know what is the best way to structure DataObjects

Currently, I have DataObjects that have a hierarchical structure but do not support INotifyProperty, although the children list is of type ObservableCollection. I have no way to implement notifypropertychange by properties.

I was wondering how to make them MVVM friendly. Implementing a partial class and adding all the properties or commands needed or wrapping all DataObjects, and keeping the list of models and the MVVM list in sync.

All thoughts and ideas are appreciated.

+4
source share
2 answers

Strict implementation of MVVM means that you must create ViewModel classes that expose all DataObjects (your model) that will be used in the View - The View, should not have direct access to the model.

After that, you will have full control over the ViewModel, and you will be able to implement the INotifyPropertyChange events and synchronize the ViewModel with the model with each notification of a change or with certain actions.

+1
source

I would agree with Bermo with a note that not many people do not strictly implement the template. You can directly pass model objects and implement INotifyPropertyChanged in these objects. But below are the main tools that you can use to implement what you have:

class PersonViewModel : INotifyPropertyChanged { Person p = new Person(); public string First { get { return p.First; } set { p.First = value; onPropertyChanged("First"); } } public string Last { get { return p.Last; } set { p.Last = value; onPropertyChanged("Last"); } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; private void onPropertyChanged(string propertyName) { if (PropertyChanged!=null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName); } } #endregion } 

I personally created the ViewModel class for inheritance so that I can put my INotifyPropertyChanged code there and not have to repeat it again. Then my implementations simply inherit from this base class.

+1
source

Source: https://habr.com/ru/post/1302237/


All Articles