MVVM / User Controls & View = ViewModel convention

The Laurent of MVVM Light fame introduced me to MVVM, and there is one representation model in a single view convention. So what is the rule for custom controls? One ViewModel for each user control? When you create a view that uses more than one user control, do you create another view model to aggregate user control view models?

Thanks in advance for your input.

Richard

+4
source share
2 answers

In my MVVM projects, I usually did what you offer: one ViewModel for UserControl with another ViewModel that combines them all together.

That aggregation of ViewModel will often be a ViewModel for a window, and not for another UserControl, although this is not necessary and may be more a result of my preferences and history, and the fact that I mainly work in WPF.

In one place where I do not have a separate ViewModel for UserControl, I create very specific reusable UserControls - such as buttons with specific visual effects or custom sliders.

This is reflected in my project structure. I have two standard folders for UserControls (which do not have ViewModels) and Views, which are either Windows or UserControls and which always have ViewModels.

+4
source

One ViewModel for each user control?

Yes, in general. User UserControl, as a rule, is nothing more than a different view. This usually means a ViewModel for each UserControl, with a "parent" virtual machine that combines it (according to the aggregation of data in the view).

However, there are exceptions: if UserControl really acts like nothing but a custom control that is not associated with a specific business, it can be a โ€œclean lookโ€. In this case, you may not want to have a virtual machine for this control at all, since it is 100% view.

+2
source

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


All Articles