在 UWP 应用程序中合并 ResourceDictionary 初始化

Merged ResourceDictionary initalization in UWP app

在我的 UWP 应用程序的开发过程中,我注意到了一些我很难解释的有趣的怪事。

我使用 MvvmLight,我决定在单独的 ResourceDictionary Core.xaml 中添加 ViewModelLocator 资源实例,它将在 [=33] 中从 MergedDictionaries 中引用=]App.xaml。 以下是App.xaml的内容:

<Application ...>
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Resources/Core.xaml" />
            <ResourceDictionary Source="Resources/Converters.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>
</Application>

Core.xaml的内容:

<ResourceDictionary ...>
    <viewModel:ViewModelLocator x:Key="Locator" />
</ResourceDictionary>

现在我假设 Core.xaml 中的资源在 App.xaml.cs 中的 InitializeComponent 方法调用期间被初始化,但是当我尝试使用 ServiceLocator class(在 MvvmLight 的 ViewModelLocator 的构造函数中设置)时 - 像这样 - ServiceLocator.Current.GetInstance<INavigationService>().Navigate<MainViewModel>(); - 我得到一个异常提示:

An exception of type 'System.InvalidOperationException' occurred in
Microsoft.Practices.ServiceLocation.dll but was not handled in user code

Additional information: ServiceLocationProvider must be set.

确实,如果我在 ViewModelLocator 的构造函数中放置一个断点,它不会在 Window 被激活之前被调用。更有趣的是 - 如果我手动引用 Locator 资源键(例如将 Debug.WriteLine(Resources["Locator"]); 放在 ServiceLocator 的调用之上),一切正常。如果我将 ViewModelLocator 资源直接移动到 App.xaml - 然后在 IntializeComponent.

期间实例化也是如此

UWP 应用程序中是否存在合并资源字典的惰性实例化?或者为什么它会这样?

UWP 中的 ResourceDictionary 没有任何代码隐藏(没有 InitializeComponent)。因此,在 ResourceDictionary 中定义的任何 class 引用都不会被直接初始化。

App.InitializeComponent 也不会为您做这件事。 UWP 中的资源字典不提供此功能 - 不要问我为什么。

您可以通过尝试在 ResourceDictionary 中初始化 DataTemplate 来轻松尝试。
遗憾的是,这应该都不起作用。

但是,在代码隐藏中使用 Resources["Locator"] 访问会触发 class 的构造函数,你没问题。

这不是解决方案,而是对您的问题的解释。 希望对你有帮助。