I have a View that displays a DataGrid
which is bound to an ObservableCollection
in the ViewModel. For the sake of discussion, let's say we have a Team
View containing a Team DataGrid
, in which each row represents a Player
.
My question is about what data type I should use to represent the players in my Team
collection. Is it a good idea for the items in the collection to be ViewModels themselves? In this case, my Team
View would be associated with a single Team
ViewModel as well as any number of Player
ViewModels (in the Team collection).
Does having multiple ViewModels associated with a single View violate any design guidelines for MVVM , and is there a preferred way of implementing this scenario?
Thanks!
Best Answer
No that is fine; each object should be a ViewModel in its own right. It makes for cleaner code, nicer interactions, and remember, if it works well then it's correct (even if it violates guidelines).
I would do it exactly the way you are prescribing. I'd bind my grid to a
Team
, which would have anObservableCollection<Player>
, wherePlayer
is another ViewModel-type class. Each row item would get thePlayer
as itsDataContext
and so you're still binding to ViewModel properties as you'd expect: andPlayer
can still havepublic
properties forICommand
s (likely RelayCommands) for manipulation!Hope that helps!