In general, having shoveled a bunch of stuff, I finally got confused. With view everything is clear, but the model and viewmodel raise questions. Suppose there is a model:

 class PersonModel{ public string Name {get; set;} public string LastName {get; set;} } 

ViewModel of this model, as I understand it, stores a link to the PersonModel , commands and communicates with the UI. Now question number 1: Who performs CRUD operations? Does the model keep itself, does ViewModel do this, or is there any manager at all? How is architecture more correct?

Question number 2: What should the ViewModel look like to work with a collection of model elements and what type of values ​​should it store? PersonModel? PersonViewModel?

If there is an intelligent manual on MVVM - I will be glad to link.

  • Not a model view, but a view model. - andreycha
  • corrected, thanks. - Ivan Nazarov

1 answer 1

I always adhere to this approach:

1) For CRUD operations use repositories that are injected through the constructor. In order not to mix all the logic in one pile.

2) ViewModel for a collection of elements and for one element are different things. Those. if you make a ViewModel for a collection, then the ViewModel will contain a collection of PersonModel elements.

Example (I use MVVMLight): For a single model:

 public interface IItemViewModel<T> where T : ObservableObject { T CurrentItem { get; set; } } public class BaseItemViewModel<T> : ViewModelBase, IItemViewModel<T> where T : ObservableObject { protected IRepository<T> Repository; private T _currentItem; public BaseItemViewModel(IRepository<T> repository) { Repository = repository; } public virtual T CurrentItem { get { return _currentItem; } set { _currentItem = value; RaisePropertyChanged(() => CurrentItem); } } } 

For a collection of models:

 public interface IItemsViewModel<T> where T : ObservableObject { T CurrentItem { get; set; } ObservableCollection<T> Items { get; set; } } public class BaseItemsViewModel<T> : ViewModelBase, IItemsViewModel<T> where T : ObservableObject { protected IRepository<T> Repository; private T _currentItem; public BaseItemsViewModel(IRepository<T> repository) { Repository = repository; } public virtual T CurrentItem { get { return _currentItem; } set { _currentItem = value; RaisePropertyChanged(() => CurrentItem); } } public virtual ObservableCollection<T> Items { get; set; } } 
  • Could you show the implementation of a specific ItemsViewModel? I can not figure out how the exchange between the repository and the ObservableCollection is implemented. In my case, you need to pull data from a text file. - Ivan Nazarov