在使用 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' 是一個變量,但像類型一樣使用
1 回答

瀟湘沐
TA貢獻1816條經驗 獲得超6個贊
將類型作為參數傳遞給Resolve(Type serviceType)
window.DataContext = container.Resolve(viewModelType);
而不是試圖將其用作通用參數
- 1 回答
- 0 關注
- 142 瀏覽
添加回答
舉報
0/150
提交
取消