如何使用仅具有视图模型类型的Autofac解析视图模型?

时间:2019-06-22 15:26:43

标签: c# wpf mvvm types datacontext

在具有Autofac容器且已注册VM的应用程序中,我需要在仅查看模型Type的情况下分配DataContext。

MainViewModel调用 NavigationService

await NavigationService.NavigateToAsync<UpdateViewModel>();

在我的服务类别中,该如何做(这很好):

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'是变量,但像类型一样使用

1 个答案:

答案 0 :(得分:1)

将类型作为参数传递给Resolve(Type serviceType)

window.DataContext = container.Resolve(viewModelType);

而不是尝试将其用作通用参数