MVVM - View model with collection of view models?
Within MVVM, can a view model have a collection of view models?
Is it okay to do:
Please assume ItemViewModel exists somewhere in the code base.
If this is acceptable, where should this collection be initialised from? The constructor or somewhere else?
12 Replies
Yes of course
I don't see a problem with that and I tend to do it myself (e.g. Wanting to bind a list of objects to checkboxes needs some sort of intermediate VM)
your example does not require VM for each item, could also set
ListView.ItemTemplate
to a custom DataTemplate in xaml. Thats what I would prefer tho 🤔
should be easy to avoid dependency between two viewmodels and to only have view depend on viewmodelI will admit my example was a simple one, just for proof of concept
Sorry I'm a little confused. Yes a custom
<DataTemplate DataType="{x:Type local:ItemViewModel}">
in xaml is how I would do it as well
But like, if you want to bind Checkbox.IsChecked
for each item, how do you do that other than wrap every item in its own ItemViewModel instance which exposes a boolean for that?
no viewmodel needed other than the one that holds
MyItems
What if
MyItem
is part of your model, perhaps even from an assembly you don't controlMyItem is the model
Right, and say there's no
IsTrue
property and you can't add it eitherwell there must be a boolean property for you to bind it to an IsChecked property...
Hence adding a shim object (a.k.a. A view model)
There is no need for a boolean - use a converter and convert any property value into a boolean
In my applications I have a domain layer where I declare any models the app will work with. These models are filled by services, providers or something and the models contains anything that is needed. Any mapping is done inside these services or providers.