views:

466

answers:

2

Hi

I can't figure out how to pass parameters to my viewmodels from other views or viewmodels.

For instance, I have a View called Customers. There is a grid inside, and if you double-click the grid, a new view is supposed to come up and allow you to edit that customer's data. But how will the View(Model) responsible for editing data know which customer it's supposed to open if I can't pass any parameters inside?

EventAggregator is out of the question because I obviously can't create hundreds of eventargs, each for one view. And besides, it's a lousy solution.

So far I was able to come up with:

CustomerDataView custView = new CustomerDataView(customerId, currentContext);
manager.Regions[RegionNames.Sidebar].AddAndActivate(custView);

What do you think about this particular solution? Is this the way it's normally done? What I don't like about this is the fact that I lose out on automatic dependency injection by Unity.

+1  A: 

That's what M is for in MVVM. E.g. have a model that is shared (injected by Unity in the constructor) by the customers grid and customer editor. When double click occurs in the gird it would set Customer instance in the model. When editor view is created its viewmodel will get Customer from the model.

As for the loss of automatic dependency injection you mentioned you could use CreateChildContainer() method. E.g.:

using (var childContainer = _container.CreateChildContainer())
{
    childContainer.RegisterInstance(customerId);
    var custView = childContainer.Resolve<CustomerDataView>();
    manager.Regions[RegionNames.Sidebar].AddAndActivate(custView);
}
PL
A: 

Alternatively, you can upgrade your Unity to the latest build, which has support for "Parameter Overrides".

MyType mt = container.Resolve<MyType>(
                      new ParameterOverride("customerId", customerId));

This is what I've done. We found that the subcontainers maintained a circular reference to their parent and wouldn't collect properly (leaked memory) so we upgraded and opted for this method.

Anderson Imes