0

我不知道如何在 MainWindowViewModel 的构造函数调用中注入参数。我想要的是在 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>();
}

主视图模型:

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

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

主窗口.xaml

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

1 回答 1

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>();
}

另请注意,您应该只绑定到 XAML 中的“Main”:

DataContext="{Binding Main, Source={StaticResource Locator}}"
于 2017-06-12T09:54:19.833 回答