2015-12-17 14 views
5

在我的UWP應用程序的開發過程中,我注意到並且雜亂無章,我很難解釋。在UWP應用程序中合併的ResourceDictionary initalization

我的用戶MvvmLight和我決定在一個單獨的ResourceDictionary Core.xaml將從MergedDictionariesApp.xaml中引用添加ViewModelLocator資源實例。 以下是內容的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.xamlInitializeComponent期間被初始化方法調用App.xaml.cs,但是當我嘗試使用ServiceLocator類(它是在ViewMode的構造函數中設置的lLocator在MvvmLight) - 這樣的 - 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的構造,它沒有窗口被激活之前調用。更有趣的是,如果我手動引用定位器資源密鑰(例如將Debug.WriteLine(Resources["Locator"]);放在ServiceLocator的呼叫之上),則一切正常。如果我將ViewModelLocator資源直接移動到App.xaml,那麼也是如此 - 然後在IntializeComponent期間將其實例化。

在UWP應用程序中是否存在合併資源字典的懶惰實例化?或者爲什麼它會這樣呢?

+1

我注意到這種奇怪的行爲發生在ResourceDictionary中有幾個正常(不是樣式)對象時。只有一個ViewModelLocator完全可以工作,並且正在調用ctor。我的發現http://stackoverflow.com/questions/34466035/uwp-resourcedictionary-is-not-being-loaded-when-i-add-a-second-object-to-it –

回答

6

UWP中的ResourceDictionary沒有任何代碼(沒有InitializeComponent)。因此,在ResourceDictionary中定義的任何類別引用都不會被直接初始化。

App.InitializeComponent也不會爲你做這件事。 UWP中的資源字典不提供這種功能 - 不要問我爲什麼。

您可以通過嘗試在ResourceDictionary中初始化DataTemplate來輕鬆嘗試此操作。
這應該 - 可悲 - 既不工作。

但是,在後面的代碼中使用Resources["Locator"]訪問會觸發類的構造函數,並且您很好。

這不是一個解決方案,而是您的問題的解釋。 我希望它可以幫助你。

+0

謝謝你的解釋!避免這個問題的一種方法是爲詞典添加一個代碼隱藏類,就像你對包含{x:Bind}的詞典所做的那樣,對吧?但我想最好是手動實例化ViewModelLocator,因爲這是直接需要的唯一資源,所以它在加載時節省內存。 –

+0

@MZetko如果它是非常重要的東西,你可以在App.xaml的Resources部分初始化它。 – Herdo