0
votes

Some basic questions, but most examples I see, only contain one view with one viewmodel and one viewmodellocator, so my questions are :

  • Does each viewmodel has it's own viewmodellocator ? (The snippet included in mvvm light toolkit for a viewmodellocator seem to imply this, as it generates a some methods eg. cleanup that has the same name for each viewmodellocator you create)
  • The views DataContext is bound to the ViewModeLocator, but how does one specify that it has an argument (eg. you want this ViewModel to retrieve a certain customer record)
2

2 Answers

1
votes

You should have only one ViewModel locator which is resposible for serving the right ViewModel for your matching view.

Usually the ViewModelLocator works together with some sort of IoC Framwork to inject right ViewModels for the right situation. Example: you have a DisgnTimeViewModel and a RuntimeViewModel and the Locator is responsible for figuring out which one to pass. Another point is... you could easily define your ViewModel in Xaml on the DataContext Property of the UserControl. This only works when your ViewModel ctor is parameterless. When you want to inject Services you would also do this via IOC and let the ViewModelLocator figure out the wiring and instanciation...

For passing around objects and arguments I would recommend looking at the concept of the EventAggregator or Messenger in MVVM Toolkit Light. The Messages are send out lously couple and every ViewModel who subscribes can receive thes messages. It is also possible to have a payload in such a message like an ID or an object...

hope this helps....

0
votes

Your ViewModelLocator (Locator) should have a property for each and every ViewModel that you have.

Example: you have an ExampleViewModel ViewModel class

  • In Locator class: ExampleViewModel should be a property
  • In View1 xaml: DataContext="{Binding ExampleViewModel, Source={StaticResource Locator}}"
  • In View2 xaml: DataContext="{Binding ExampleViewModel, Source={StaticResource Locator}}"

You should be able to bind to any of your ViewModels that you've specified in the Locator AND in as many Views as you want (not 100% sure about 2nd part).