我学习建立使用MVVM的应用程序,我有以下情况:ViewModel应该如何与存储库交互?
- 一个ViewModel应显示
Examination
类型的对象的列表。该列表将在视图中被数据绑定到ListView
,从中将被过滤,并且用户将选择ActiveExamination
以供进一步使用。 - “存在于”模型层中的存储库应该“表现为域内对象的内存中集合”,并在ViewModel内实例化。
现在我的问题是:如果存储库BE集合是数据绑定到视图,或者它应该只是实现INPC的属性的“数据源”?例如,从以下可能性中,其中一个是正确的,另一个是错误的,或者两个都是错误的?
// example where the list is replaced in order to be changed;
// ViewModel class (part of it)
public class ThisViewModel : ViewModelBase {
public List<Examination> ExaminationList {
get { return _examinationList; }
set { _examinationList = value;
NotifyOfPropertyChange("ExaminationList"); }
}
}
var repo = new ExaminationRepository();
ThisViewModel.ExaminationList = repo.getAll().where(ex => ex.Value > 20).ToList();
第二个选项
// Example where the very property IS a repository
// ViewModel class (part of it)
public class ThisViewModel : ViewModelBase {
// the List is actually a repository in disguise.
IEnumerable _examinationList = new ExaminationRepository();
public List<Examination> ExaminationList {
get { return _examinationList; }
set { _examinationList = value;
// This should be "NotifyOfCollectionChange", I guess...
NotifyOfPropertyChange("ExaminationList"); }
}
}
最有可能的,我很困惑/错在这里,但我的应用程序是相当小的,简单的架构的角度来看,我真的不打算使用大多数的框架和我已经看到了与这类问题(ORM,IoC,DI)相关的高级概念,相反,我主要关注“如何在WPF/MVVM数据绑定环境中正确处理基于可变的,基于reppository的集合”。
编辑:关于我的应用程序的一些上下文: 该应用程序执行临床检查。它有一个患者名单,每个患者都有自己的考试。有一个Patient存储库和一个Examinations存储库。当我在PatientList中选择患者时,该患者的ExaminationsList将显示Examinations回购中的匹配检查。用户对患者和检查的操作是CRUD,或者是最具体的BREAD(浏览,阅读,编辑,添加和删除)。
感谢您的任何建议!
“如何在WPF/MVVM Databinding环境中正确处理基于可变的,基于reppository的集合”---为什么要让它变得可变?你不想让它变成一成不变吗?这取决于您想如何使用ExamList的情况,是否仅仅显示数据库中的数据,而用户无法将项目添加回数据库? –
@LeoLorenzoLuis我用更多的上下文编辑了这个问题。 – heltonbiker
然后我会做的是使一个ObservableCollection属性和延迟加载支持属性来获取数据库中的项目,并且任何后续项目集合将被正确处理,当他们添加/编辑/删除。你的图层分离很好,你只需要在ViewModel中正确使用它。我不同意Sheridan的回答,你应该总是有单独的集合来填充/显示在UI中。没有什么不可以。 –