Reputation: 401
I am starting to explore the MVVM light and start to design my different viemModels. I have browsed for long time to find out what I am looking for but I could not get it :-(.
One sample I have is based on a single MainViewModel, which is handled inside a ModelViewLocator. In most cases we will have more than one viewModel, so should all viewModels be defined in a single ViewModelLocator file or do I have to have one ViewModelLocator per view?
In other words do I need to get this : MainViewModel -> MainViewModelLocator PictureViewModel -> PictureViewModelLocator
Ok fine but sill one question: let say that I have 3 viewModels that I have create as ViewModel1, 2 and 3 In ViewModelLocation, I have create same structure as the MainViewModel in order to create the instance of it and have create a main property to access Models instance.
The problem I have found is that If each of my Views corresponding to each viewModels is set to is own datacontext as ViewModelLocator.ViewModelx, the view instance is create at design time and it makes me trouble if during the constructor of my view I need to call an external class which get data from a WCF service. It generate an "instance creation error".
In an other hand if in each view I bind then NOT from ViewModelLocator.ViewModelx but instead as directly ViewModelx then I do not get that error and works better.
So what is the properway to do and the logic path :
1 - Does the MainViewModel should create all other viewModel's ? 2 - Does each View must be bound to it's own MainStatic propery in ViewModelLocator ? 3 - Does each View create their own Instance of ViewModel ?
The way I have done is that my View which return service data from an external class during ViewModel constructor creation works only if I bind it directly to the ViewModel, does it have trouble doing it so ?
Upvotes: 1
Views: 2289
Reputation: 715
Usually there is no need for multiple view model locators. The common way is to create one ViewModelLocator which you then add to Application.Resources
in App.xaml so it's available to be used anywhere in the application. Just create a property in the ViewModelLocator for each ViewModel you're using.
Below is an example which is using the IoC container in MVVM Light 4 (beta) to instantiate view models. You could also do without the IoC container but in more complex scenarios it'll definitely simplify your code:
public class ViewModelLocator
{
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register<DetailsViewModel>();
}
public MainViewModel MainViewModel
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
public DetailsViewModel DetailsViewModel
{
get
{
return ServiceLocator.Current.GetInstance<DetailsViewModel>();
}
}
}
Upvotes: 4