1

我试图将我的ShellPage的Dispatcher注入到ViewModel中,使用Unity和Prism。由于调度程序在创建shell后可用,因此我无法及时注册调度程序。
第一步:将Dispatcher注入ViewModel - 重构Unity - 属性注入

protected override Task OnInitializeAsync(IActivatedEventArgs args) 
     { 
      [...] 
      Container.RegisterInstance<IResourceLoader>(resourceLoader); 

其次,CreateShell方法将被执行。

protected override UIElement CreateShell(Frame rootFrame) 
     { 
      var shell = Container.Resolve<ShellPage>(); 
      Container.RegisterType<MyViewModel>(new InjectionProperty(nameof(MyViewModel.Dispatcher), shell.Dispatcher)); 

尽管我将Dispatcher插入到MyViewModel中,但属性Dispatcher为null。也许我需要在MEF中重新构建一些东西?我怎样才能实现在MyViewModel中的属性注入?

回答

0

我认为是不可能的。 不支持重新构建像MEF。

最简单的方法是创建一个帮手来获得当前视图的调度,并在您的ViewModels使用它

请看下面的例子: http://mikaelkoskinen.net/post/fixing-coredispatcher-invoke-how-to-invoke-method-in-ui-thread-in-windows-8-release-preview

这个例子是为Windows 8,但你可以使用它UWP应用

只是当我用这个方法,我做UWP应用小的变化:

在Onlaunched事件app.xaml.cs

我在不同的地方添加了UIDispatcher。

if (rootFrame.Content == null) 
     { 
      // When the navigation stack isn't restored navigate to the first page, 
      // configuring the new page by passing required information as a navigation 
      // parameter 

      UIDispatcher.Initialize(); 
      rootFrame.Navigate(typeof(MainPage), e.Arguments); 
     } 
     // Ensure the current window is active 
     Window.Current.Activate();