Reputation: 628
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?
Upvotes: 0
Views: 444
Reputation: 37164
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 as ObservableCollection<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 an ObservableCollection<T>
instead of a list because ObservableCollection<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 ItemsSource
property will be set to bind to the Product
collection. You can then have methods inside of your ViewModel that will be responsible for communicating with your data store to populate the observable collection.
public class MyViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private ObservableCollection<Product> _products = null;
public ObservableCollection<Product> Products
{
get { return _products; }
set
{
if( _products != value )
{
_products = value;
if( this.PropertyChanged != null )
{
this.PropertyChanged( this, new PropertyChangedEventArgs( "Products" ) );
}
}
}
}
// have code in here that loads the Products list from your data store (i.e. service call to database)
}
public MyView()
{
InitializeComponent();
this.DataContext = new MyViewModel();
}
<ListBox
ItemsSource={Binding Path=Products, Mode=OneWay}
SelectedItem={Binding Path=SelectedProduct, Mode=TwoWay}
...
/>
Upvotes: 1