-
-
Notifications
You must be signed in to change notification settings - Fork 4
π View Model Locator
Marc Rousavy edited this page May 26, 2020
·
2 revisions
The View-Model Locator helps initializing and injecting View-Models and it's dependencies.
Begin by creating the View-Model Locator object:
public class ViewModelLocator
{
private readonly IInjector _injector = new Injector();
public UserViewModel UserViewModel => InjectionResolver.InjectConstructor<UserViewModel>(_injector);
// other view models go here
}
You can use a static singleton instance for the
injector
parameter - See Dependency Injection π
The ViewModelLocator
has to be registered in the Application Resources:
<Application ...>
<Application.Resources>
<local:ViewModelLocator x:Key="ViewModelLocator" />
</Application.Resources>
</Application>
To locate a View-Model, just bind to it using the ViewModelLocator
as your Source
:
<UserControl
...
DataContext="{Binding UserViewModel, Source={StaticResource ViewModelLocator}}">
This will automatically invoke the InjectConstructor()
call and return an initialized UserViewModel
instance.
See What is a ViewModelLocator? π and View Model Locator in WPF π