MVVM / User Controls & View = ViewModel convention
Laurent of MVVM Light fame introduced me to MVVM, and the convention of one view has one view model. So what is the rule of thumb for user controls? One ViewModel for each user control? When creating a View leveraging more than one user control, do you create another viewmodel to aggregate the 开发者_开发知识库user control view models?
Thanks in advance for the input.
Richard
In my MVVM projects I have tended to do what you suggest: one ViewModel per UserControl with another ViewModel that aggregates these all together.
That aggregating ViewModel will often be the ViewModel for a window rather than another UserControl - though that isn't necessary and may well be more a result of my preferences and history and the fact I mainly work in WPF.
The one place where I don't have a seperate ViewModel for a UserControl is where I create very specific reusable UserControls - things like buttons with specific visual effects, or custom sliders.
That 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.
One ViewModel for each user control?
Yes, in general. A UserControl, typically, is nothing but another View. This usually means a ViewModel per UserControl, with a "parent" VM aggregating it (to match up with the View aggregating the data).
There are exceptions, however: If the UserControl is really acting as nothing but a custom control, not bound to something business specific, it may be "pure view". In this case, you may not want to have a VM at all for that control, as it's 100% View.
精彩评论