我不知道如何在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}}"
答案 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}}"