I am refactoring my application to utilize MVVM. I used to keep a List<Product> variable in the Application class that I was able to bind a ListView to. This List made up my Data layer. The Page with this ListView is a master/detail layout. With MVVM, I am thinking that the List should now hold instances of the ProductModel as it is the data layer. If I should be binding to ViewModels, do I need a separate List of ViewModels too?
I am refactoring my application to utilize MVVM. I used to keep a List<Product>
Share
You might need to take a different perspective on MVVM. Your View is the page with the controls (XAML) and your ViewModel is the glue between your data model and the page. The View’s entire data context will be set to the ViewModel (done either in the XAML directly or in code-behind depending on which MVVM camp you subscribe to).
In your example, you would move
List<Product>onto the ViewModel asObservableCollection<Product>and make sure that your ViewModel implements the INotifyPropertyChanged interface. INotifyPropertyChanged is the contract the View uses to know when to update it’s binding. You will use anObservableCollection<T>instead of a list becauseObservableCollection<T>implements INotifyPropertyChanged itself.Your View’s DataContext property will be set to an instance of the ViewModel. On the View, the ListBox control’s
ItemsSourceproperty will be set to bind to theProductcollection. You can then have methods inside of your ViewModel that will be responsible for communicating with your data store to populate the observable collection.ViewModel
View Code-Behind
View