Reputation: 1063
I'm trying to understand what's the best way to work with a viewmodel and with the model that stays behind.
My model is a collection of custom items (like a list of user configurations).
I understand that the correct way to expose this model is through a ConfigurationListViewModel
that converts the model's list in data readable by the ui.
But how should I manage the items that lies behind the ConfigurationListViewModel
?
Should the single configuration itself have a ConfigurationViewModel
?
Or the main ConfigurationListViewModel
should handle the exposure of its items?
If I want to add a Configuration to my ConfigurationList
, I call an Add()
method to my ConfigurationListViewModel
, and it creates in itself a new Configuration
, or should I create a new (Configuration
? ConfigurationViewModel
?) in the parent, and then call an Add
([Configuration
?ConfigurationViewModel
?]newConf)
?
Upvotes: 1
Views: 125
Reputation: 46
In my experience the ConfigurationListViewModel
containing an ObservableCollection<ConfigurationViewModel>
is the best (most flexible and cleanest) way.
Just for displaying selected items differently than non-selected items, it's useful when the items know about their selected state. And because selection is nothing the model should care about, you need a ConfigurationViewModel
with an IsSelected
property.
Updates (add, delete items) of the list (if triggered by the user/UI) should be done mainly by the model. (It's the model's responsibility to know how new item are initialized, for example.) And the ListViewModel should then change accordingly: create a viewmodel from the newly created model item or delete the viewmodel whose item was deleted in the model.
Upvotes: 0
Reputation: 61379
Really, the answer is any of the above.
If the data used in the view model has a form identical to that of the model, you aren't doing yourself any favors by creating a ConfigurationViewModel
class that is just a copy of the Configuration
class.
As to adding, you can do it either way. Sometimes you want to do all your editing in the view model so you can "revert" the changes by not actually modifying the model. If that's not a concern, modifying the model first and propagating to the view model is just as valid of an approach.
All that being said, none of your approaches will violate MVVM. Pick what makes the most sense, especially semantically and for future maintenance. In general, I prefer simplicity to blind adherence to a principle such as "every data object needs a view model representation".
Upvotes: 2