wpfmvvmdependency-injectionmvvm-lightviewmodellocator

How to handle dependency injection with mvvmlight


i've no clue how to inject a parameter in the constuctor call of the MainWindowViewModel. What i want is to register an instance of the current mainwindow (this) in the viewmodellocator. How can i accomplish this?

This is my situation in the viewmodellocator class:

public ViewModelLocator()
{
    ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

    //SimpleIoc.Default.Register<Window>();  //THIS IS NOT WORKING BECOUSE ITS A NEW INSTANCE, I NEED THE INSTANCE OF THE CURRENT MAINWINDOW HERE.
    SimpleIoc.Default.Register<MainWindowViewModel>();
}

MainViewModel:

public MainWindowViewModel(Window window)
{
    this.Window = window;

    //Listen out for the window resizing
    this.Window.StateChanged += StateChanged;
}

MainWindow.xaml

DataContext="{Binding MainWindow, Source={StaticResource Locator}}"

Solution

  • If you want a Window to be resolved to your MainWindow:

    public ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
    
        SimpleIoc.Default.Register<System.Windows.Window>(() => System.Windows.Application.Current.MainWindow as MainWindow);
        SimpleIoc.Default.Register<MainViewModel>();
    }
    

    Also note that you should bind to just "Main" in your XAML:

    DataContext="{Binding Main, Source={StaticResource Locator}}"