Search code examples
xamldatatemplatewin-universal-appresourcedictionary

DataTemplate not found in merged ResourceDictionary


I'm currently developing a universal app for Windows Phone 8.1 and Windows 8.1. I share most of my code, but I'm willing to keep style resources appart.

Some context : First, right now I've only started the WP8.1 projects so everything is related to this platform. In this WP8.1 project, I have a MainPage.xaml which contains a Pivot control. One of the PivotItem is a UserControl called, for clarity purposes, MyUserControl.

I created a resource dictionary Styles.xaml into my "Assets" directory, in BOTH platform projects. Then, I registered those 2 new files into my shared App.xaml like this :

<Application.Resources>
    <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
    <ResourceDictionary x:Key="ResourceDictionary">
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Assets/Styles.xaml"></ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

In the WP8.1 project Styles.xaml file, I created a DataTemplate :

<DataTemplate x:Key="MyDataTemplate">
    <TextBlock Text="This is a textblock" />
</DataTemplate>

In MyUserControl, I've added a ListView and bound it on the ItemTemplate property to MyDataTemplate like this :

<ListView ItemTemplate="{StaticResource MyDataTemplate}" ItemsSource="{Binding MyContent}" />

When I run the solution and I end up with this error :

Cannot find a Resource with the Name/Key "MyDataTemplate"

Does anyone know why I encounter this error ? What did I do wrong ?

An odd thing : when I right click > "Go To Definition" on the MyDataTemplate bound in the ListView.ItemTemplate property, it routes me to the right place.

Thank you in advance for your help !


Solution

  • Your code is wrong, here is the correct one

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/Assets/Styles.xaml"></ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
            <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
        </ResourceDictionary>
    </Application.Resources>