与单个视图关联的多个ViewModel [英] Multiple ViewModels associated with a single view
问题描述
我有一个显示DataGrid
的视图,该视图绑定到ViewModel中的ObservableCollection
.为了便于讨论,假设我们有一个Team
视图,其中包含一个团队DataGrid
,其中每一行代表一个Player
.
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
.
我的问题是我应该使用哪种数据类型来表示Team
集合中的玩家.集合中的项目本身就是ViewModels是一个好主意吗?在这种情况下,我的Team
视图将与单个Team
ViewModel以及任意数量的Player
ViewModels(在Team集合中)相关联.
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).
具有与单个View关联的多个ViewModel是否违反MVVM的任何设计准则,并且有实现该方案的首选方法吗?
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?
谢谢!
推荐答案
不,这很好.每个对象本身应为ViewModel.这样可以使代码更简洁,交互效果更好,并记住,如果效果良好,那么它是正确的(即使它违反了准则).
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).
我会完全按照您的处方进行操作.我将网格绑定到Team
,该网格将具有ObservableCollection<Player>
,其中Player
是另一个ViewModel类型的类.每个行项目都将Player
作为其DataContext
,因此您仍按预期绑定到ViewModel属性:并且Player
对于ICommand
仍可以具有public
属性(可能是RelayCommands)进行操纵!
I would do it exactly the way you are prescribing. I'd bind my grid to a Team
, which would have an ObservableCollection<Player>
, where Player
is another ViewModel-type class. Each row item would get the Player
as its DataContext
and so you're still binding to ViewModel properties as you'd expect: and Player
can still have public
properties for ICommand
s (likely RelayCommands) for manipulation!
希望有帮助!
这篇关于与单个视图关联的多个ViewModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!