Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM for collections

Tags:

mvvm

wpf

I have recently started learning wpf and am trying to use mvvm.

My understanding is that in the mvvm neither the view or the model should know the other exists.

What I am trying to do is show a list of customers on the screen. But if I code the viewModel as shown below. which is similar to many examples I see on the net, then I end up with some code looking like this

class Customer 
{    
    public String Name {get;set;}     
    public String Address {get;set;} }
}

class MainWindowViewModel
{
    ObservableCollection<Customer> customers = new ObservableCollection<Customer>();

    public ObservableCollection<Customer> Customer 
    {
      get {return customers;}
    } 

    public MainWindowViewModel() 
    {
     //cust1 and cust2 are Customer objets
      customers.Add(cust1);
      customers.Add(cust2);
    }
}

Now if I create an instance of my MainWindowViewModel and set it as the datacontext of my MainWindowView (my view) and i further bind the viewmodels Customers property to a listBox, then the view will need a reference to the assembly that contains my Models.

So my questions are.

1) Is adding a reference to Models assembly allowable in MVVM, since this would mean the view knows about the model.

2) would a better solution be to wrap each Customer object in a CustomerViewModel and have the MainWindowViewModel contain ObservableCollection of CustomerViewModel instead of ObservableCollection of Customer. This would separate the models completely from the view.

like image 413
CAA Avatar asked Jun 10 '11 08:06

CAA


1 Answers

  1. I'm not sure why you think the project containing your views requires a reference to your model project? There is nothing in your view which references your models directly - your binding expressions in XAML are linked by name only, and to properties on your view model anyway, not your model.
  2. Wrapping your model in a view model is a good option if your view requires additional data than your model provides, and it is undesirable to change your model. For example, you view may need to display the Age of a User type, but User only has a DateOfBirth property. Creating a UserViewModel with an Age property would be a good option if you didn't want to alter your model.
like image 75
devdigital Avatar answered Sep 28 '22 14:09

devdigital