如何使用仅具有视图模型类型的 Autofac 解析视图模型?
How to Resolve View Model with Autofac having just Type of the view model?
在使用 Autofac 容器并注册了 VM 的应用程序中,我需要在只有视图模型类型的情况下分配 DataContext。
MainViewModel 调用 NavigationService:
await NavigationService.NavigateToAsync<UpdateViewModel>();
在我的服务 class 中,该怎么做(这很好):
private async Task InternalNavigateToAsync(Type viewModelType, object parameter)
{
var bootStrapper = new BootStrapper();
var container = bootStrapper.BootStrap();
Window window = CreateWindow(viewModelType, parameter);
//this works fine
if (viewModelType.Name == "MainViewModel")
{
window.DataContext = container.Resolve<MainViewModel>();
}
if (viewModelType.Name == "UpdateViewModel")
{
window.DataContext = container.Resolve<UpdateViewModel>();
}
window.Show();
}
这个(不工作):
private async Task InternalNavigateToAsync(Type viewModelType, object parameter)
{
var bootStrapper = new BootStrapper();
var container = bootStrapper.BootStrap();
Window window = CreateWindow(viewModelType, parameter);
//but how to do this?
window.DataContext = container.Resolve<viewModelType>();
window.Show();
}
它给我一个错误:
'viewModelType' is a variable but is used like a type
将类型作为参数传递给 Resolve(Type serviceType)
window.DataContext = container.Resolve(viewModelType);
而不是尝试将其用作通用参数
在使用 Autofac 容器并注册了 VM 的应用程序中,我需要在只有视图模型类型的情况下分配 DataContext。
MainViewModel 调用 NavigationService:
await NavigationService.NavigateToAsync<UpdateViewModel>();
在我的服务 class 中,该怎么做(这很好):
private async Task InternalNavigateToAsync(Type viewModelType, object parameter)
{
var bootStrapper = new BootStrapper();
var container = bootStrapper.BootStrap();
Window window = CreateWindow(viewModelType, parameter);
//this works fine
if (viewModelType.Name == "MainViewModel")
{
window.DataContext = container.Resolve<MainViewModel>();
}
if (viewModelType.Name == "UpdateViewModel")
{
window.DataContext = container.Resolve<UpdateViewModel>();
}
window.Show();
}
这个(不工作):
private async Task InternalNavigateToAsync(Type viewModelType, object parameter)
{
var bootStrapper = new BootStrapper();
var container = bootStrapper.BootStrap();
Window window = CreateWindow(viewModelType, parameter);
//but how to do this?
window.DataContext = container.Resolve<viewModelType>();
window.Show();
}
它给我一个错误:
'viewModelType' is a variable but is used like a type
将类型作为参数传递给 Resolve(Type serviceType)
window.DataContext = container.Resolve(viewModelType);
而不是尝试将其用作通用参数