MVVM: Thin ViewModels and Rich Models

前端 未结 4 1257
小鲜肉
小鲜肉 2021-01-02 02:35

I\'m continuing to struggle with the MVVM pattern and, in attempting to create a practical design for a small/medium project, have run into a number of challenges. One of t

相关标签:
4条回答
  • 2021-01-02 03:21

    I think INotifyPropertyChanged on your model is only useful when you're expecting it to be operated on by your VM and external "forces" simultaneously.

    I'm personally a supporter of POCO models. Putting any framework-specific scaffolding into my model would make me worry. When you put an event into your model class you have to consider carefully possible issues with your model's life-cycle, serialization, storage etc. For example what happens if you recreate your object from data source and old INotifyPropertyChanged subscriptions are now invalid?

    Similarily better place for ObservableCollection is in the VM, which can consume an IEnumerable datasource, and present to the view only selected or ad hoc filtered items.

    0 讨论(0)
  • 2021-01-02 03:24

    Disclaimer - I am not an expert -

    I do not put INotifyChanged on my Models. I had done this at first but came to the simple realization that INotifyChanged is really only practical for notifying the UI so I only put INotifyChanged on my ViewModels now. This has made it easier to control the number of "RaisePropertyChanged"... My views never reference a Model directly.

    I'm working on my first MVVM project yet on my 3rd major refactor :P

    0 讨论(0)
  • 2021-01-02 03:34

    I agree that there will be tight coupling between the View and ViewModel. But this can be alleviated to some extent by using IValueConverters whenever possible to do transformations.

    I try to keep my business logic in my ViewModel. Also, I use the Viewmodel to change the shape of my Model to fit that which the View might expect.

    0 讨论(0)
  • 2021-01-02 03:42

    I consider this to be the pragmatic approach - we have followed this pattern successfully in the past.

    The basic premis was to bind directly to a model that implements INotifyPropertyChanged for most read-only data, and then add extra properties to the viewmodel for view specific stuff that needs to be transformed (as you suggested). For non read-only properties, we found it easiest the create viewmodel entries (generally of type string) as this allows client-side validation to be added easily in the viewmodel.

    0 讨论(0)
提交回复
热议问题