如何使用mvvmlight处理依赖注入

时间:2017-06-12 09:23:24

标签: wpf mvvm dependency-injection mvvm-light viewmodellocator

我不知道如何在MainWindowViewModel的constuctor调用中注入参数。我想要的是在viewmodellocator中注册当前主窗口(this)的实例。我怎么能做到这一点?

这是我在viewmodellocator类中的情况:

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}}"

1 个答案:

答案 0 :(得分:1)

如果您希望将Window解析为MainWindow

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

    SimpleIoc.Default.Register<System.Windows.Window>(() => System.Windows.Application.Current.MainWindow as MainWindow);
    SimpleIoc.Default.Register<MainViewModel>();
}

另请注意,您应该只绑定&#34; Main&#34;在您的XAML中:

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