3

I am trying to implement an application with the MVVM Light Toolkit, but I am somehow stuck with the ViewModelLocator.

While it is clear to me how to access it from the views in XAML and code-behind of the views, I have some problems accessing it from other view models.

In App.xaml:

<Application.Resources>
  <vm:ViewModelLocatorTemplate xmlns:vm="clr-namespace:MvvmLight1.ViewModel" x:Key="Locator" />
</Application.Resources>

In the View:

DataContext="{Binding Source={StaticResource Locator}, Path=ViewModelName}"

But how to access for example the MainViewModel from some other view model? It seems previous releases of the ViewModelLocator snippets had a static method to the different view models. But those do not exist anymore, so I assume this was not the way to go. But what is? Or am I doing something completely against the pattern if I want to access the locator from a view model?

2 Answers 2

11

Depends a bit on how you have set up the view model locator, but normally you should be using an IOC container to register all the different ViewModels.

For example when using the one of MVVM Light it would be like this: SimpleIoc.Default.Register<MainViewModel>();

So when this is available, you can use that in any other class - so also in another viewmodel by using: SimpleIoc.Default.GetInstance<MainViewModel>();

Or if you told the ServiceLocator you are using SimpleIoc it would be like this: ( the registering ) ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

And getting it back ServiceLocator.Current.GetInstance<MainViewModel>();

2
  • 2
    Yes, this kind of code is inside the ViewModelLocator. So your suggestion is to use the SimpleIoc directly instead of the the class ViewModelLocator?
    – MuhKuh
    Commented Nov 5, 2015 at 21:18
  • 2
    Yes, because that is why you added the Ioc in the first place :) for 'injection' so to use those class instances in any other class.
    – Depechie
    Commented Nov 5, 2015 at 21:27
4

Depechie's answer is correct in suggesting that you use the IoC container to retrieve the ViewModels in the same way that the ViewModelLocator does.

I will however propose another method that will retrieve the ViewModel in the same way that it is done in your XAML.

XAML (Page.xaml)

DataContext="{Binding Source={StaticResource Locator}, Path=ViewModelName}"

Code (Page.xaml.cs)

this.DataContext = (App.Current.Resources["Locator"] as ViewModelLocator).ViewModelName

The above pieces of XAML and Code are equivalent. I hope this helps you undestand the process the app does to retrieve the ViewModels.

2
  • This should be the correct answer. Depechie's answer is an anti-pattern.
    – IamDOM
    Commented Dec 8, 2020 at 17:11
  • You're missing an opening ( before the App.Current.
    – IamDOM
    Commented Dec 8, 2020 at 17:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.