据我理解,MVVM 模式中的 ModelX 类应该被 XViewModel 类隐藏起来,以便 XViewModel 注意到对模型所做的任何更改并防止其他类访问该类。但是有一个问题,我无法解决。
假设我有一些类: ProjectModel、UserModel 和 GroupModel。 ProjectModel 包含一个 UserModel 列表和一个 GroupModel 列表,其中包含一个 UserModel 列表。
对于所有这些类,都存在 ViewModel: ProjectViewModel、UserViewModel 和 GroupViewModel。 ProjectViewModel 将所有模型列表包装成 ObservableCollection(如果需要更改),否则为 ReadOnlyCollection。在我的情况下,它是 ObservableCollection。
现在想象一下,我想将一个组添加到项目中。因此,我调用类似以下内容的东西:
现在,GroupViewModel的构造函数需要通过调用GroupModel的构造函数来创建其字段_groupModel:
但是不幸的是,GroupViewModel无法访问UserViewModel的_user字段,因此它不能创建自己的_groupModel字段。
我遇到过这个问题不止一次,但是无论在Google还是这里,我都找不到一个好的解决方案。
我想到的可能的解决方案有:
1.通过在每个ViewModel类中持有一个属性来授予对模型的访问权限。但是这与隐藏模型以防未经授权的访问的想法相冲突。
2.在UserViewModel中实现一个“public static GroupModel CreateGroup()”,因为它可以访问其模型。但是这听起来有点不太好。
你是怎么解决这个问题的?我在MVVP模式上错过了什么吗?
假设我有一些类: ProjectModel、UserModel 和 GroupModel。 ProjectModel 包含一个 UserModel 列表和一个 GroupModel 列表,其中包含一个 UserModel 列表。
对于所有这些类,都存在 ViewModel: ProjectViewModel、UserViewModel 和 GroupViewModel。 ProjectViewModel 将所有模型列表包装成 ObservableCollection(如果需要更改),否则为 ReadOnlyCollection。在我的情况下,它是 ObservableCollection。
现在想象一下,我想将一个组添加到项目中。因此,我调用类似以下内容的东西:
UserViewModel user1 = new UserViewModel("Chriss");
UserViewModel user2 = new UserViewModel("Jena");
ProjectViewModel project = new ProjectViewModel();
project.Groups.Add(new GroupViewModel(user1, user2));
现在,GroupViewModel的构造函数需要通过调用GroupModel的构造函数来创建其字段_groupModel:
public GroupModel(UserModel user1, UserModel user2){}
但是不幸的是,GroupViewModel无法访问UserViewModel的_user字段,因此它不能创建自己的_groupModel字段。
我遇到过这个问题不止一次,但是无论在Google还是这里,我都找不到一个好的解决方案。
我想到的可能的解决方案有:
1.通过在每个ViewModel类中持有一个属性来授予对模型的访问权限。但是这与隐藏模型以防未经授权的访问的想法相冲突。
2.在UserViewModel中实现一个“public static GroupModel CreateGroup()”,因为它可以访问其模型。但是这听起来有点不太好。
你是怎么解决这个问题的?我在MVVP模式上错过了什么吗?