This project has moved and is read-only. For the latest updates, please go here.

WAF ViewModel as an element of collection

Nov 18, 2009 at 10:26 PM

I'm trying to take WAF as startup for my project. I have such situation - I need to make a collection of ViewModels inside another VM. Just like in demo app of Josh Smith's MSDN article. Here is simplified example of code:

void CreateAllCustomers()
     List<CustomerViewModel> list = new List<CustomerViewModel>();
     foreach (Customer customer in customersRrepository.GetCustomers())
        list.Add(new CustomerViewModel(customer)); 


       this.AllCustomers = new ObservableCollection<CustomerViewModel>(list);

But in WAF abstract class ViewModel has only constructors with IView interface as a mandatory parameter. So what is the right way here to do? To get every instance of VM from MEF's container? Something Like this:

customerViewModel = container.GetExportedValue<CustomerViewModel>();

but would it be a good decision to initiate an instance of a View for each VM? I think, it is a some kind of memory waste. I'd prefer to make a datatemplate for collection's item of type CustomerViewModel, I even have no idea, if it possible to use View stored in a property of item for rendering a whole collection on a form.
Thanks in advance!

Nov 28, 2009 at 5:08 PM

Hi wazzzuup,

I see two possible solutions for your scenario:

  1. Use MEF to create every ViewModel. You are able to reuse the View instance when you register the View as shared (singleton) object in the MEF container. Shared is the default mode in MEF and so you just don’t apply the PartCreationPolicy attribute.
  2. When you like to use DataTemplates then it’s not possible to derive from the ViewModel class. However, you might derive from the Model class instead to get data binding support.

I hope this helps.