【问题标题】:How to Resolve View Model with Autofac having just Type of the view model?如何使用仅具有视图模型类型的 Autofac 解析视图模型?
【发布时间】:2019-06-22 15:26:43
【问题描述】:

在使用 Autofac 容器并注册了 VM 的应用程序中,我需要在我刚刚查看模型类型的情况下分配 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' 是一个变量,但用作类型

【问题讨论】:

  • 将类型作为参数传递window.DataContext = container.Resolve(viewModelType);

标签: c# wpf mvvm types datacontext


【解决方案1】:

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

window.DataContext = container.Resolve(viewModelType);

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

【讨论】:

  • 好的,我花了最后 5 个小时来解决这个问题。它是如此简单。谢谢!
猜你喜欢
  • 1970-01-01
  • 2014-04-20
  • 2013-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-07
相关资源
最近更新 更多