我學習建立使用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中。沒有什麼不可以。 –