问题
I have a UWP application for Windows 10 with MVVM Light plugged in. I store a ViewModelLocator in the App.Resources. When I have just a ViewModelLocator in my App.Resources, everything works fine.
<Application.Resources>
<viewModel:ViewModelLocator x:Key="Locator" />
</Application.Resources>
As soon as I add a String, Converter or something similar, application doesn't crash but the ViewModelLocator constructor is not being called anymore. No errors or exceptions being thrown, just ResourceDictionary is not being loaded or fails during load.
<Application.Resources>
<viewModel:ViewModelLocator x:Key="Locator" />
<x:String x:Key="SampleString">Hello</x:String>
</Application.Resources>
If I add a Style, DataTemplate, Brush, Color - everything works fine.
Haven't noticed that behavior on Windows Phone 8, Silverlignt or WPF before. Moving styles or objects to separate ResourceDictionaries and load them using MergedDictionaries didn't help.
I would like to have a list of objects in ResourceDictionary so that all constructors of these objects are being called automatically on the app start. Please advise.
P.S.: Even two similar converters don't work, while one is created without any problem
<Application.Resources>
<!--<viewModel:ViewModelLocator x:Key="Locator" />-->
<converters:StringFormatConverter x:Key="StringFormat1" />
<converters:StringFormatConverter x:Key="StringFormat2" />
</Application.Resources>
Looking for an example of ResourceDictionary usage, found similar question: Merged ResourceDictionary initalization in UWP app
回答1:
That's all because of lazy initialization. I've made some experiments and figured out this picture. I hope you will catch the idea. http://screencast.com/t/mxyBGBDuZ
回答2:
Try adding them in a Resource Dictionary like this
<Application.Resources>
<ResourceDictionary>
<viewModels:ViewModelLocator x:Key="Locator"/>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="XAMLResources/Styles.xaml" />
<ResourceDictionary Source="XAMLResources/DataTemplates.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
If you want to take a look at a complete example the code snippet is from this repository on GitHub https://github.com/AppCreativity/Kliva
You will notice we add our Converters in the Styles.xaml and that is working fine...
来源:https://stackoverflow.com/questions/34466035/uwp-resourcedictionary-is-not-being-loaded-when-i-add-a-second-object-to-it