将 Dispatcher 注入 ViewModel - Recompose Unity - 属性 注入
Inject Dispatcher into ViewModel - Recompose Unity - property injection
我正在尝试使用 Unity 和 Prism 将我的 ShellPage 的 Dispatcher 注入到我的 ViewModel 中。因为dispatcher是在shell创建之后可用的,所以没能及时注册Dispatcher。
第一步:
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 为空。也许我需要在 MEF 中重新组合之类的东西?如何实现属性注入MyViewModel?
我觉得不可能。
不支持像 MEF 那样重组。
最简单的方法是创建一个助手来获取当前视图的 Dispatcher 并在您的 ViewModels 中使用它
此示例适用于 Windows 8,但您可以将其用于 UWP 应用
就在我使用这种方法时,我对 UWP 应用程序做了一些小改动:
在 app.xaml.cs
的 Onlaunched 事件中
我在不同的地方添加了 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();
我正在尝试使用 Unity 和 Prism 将我的 ShellPage 的 Dispatcher 注入到我的 ViewModel 中。因为dispatcher是在shell创建之后可用的,所以没能及时注册Dispatcher。
第一步:
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 为空。也许我需要在 MEF 中重新组合之类的东西?如何实现属性注入MyViewModel?
我觉得不可能。 不支持像 MEF 那样重组。
最简单的方法是创建一个助手来获取当前视图的 Dispatcher 并在您的 ViewModels 中使用它
此示例适用于 Windows 8,但您可以将其用于 UWP 应用
就在我使用这种方法时,我对 UWP 应用程序做了一些小改动:
在 app.xaml.cs
的 Onlaunched 事件中我在不同的地方添加了 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();