How to use ResourceDictionary as StaticResource in Windows Phone 8

TheBlueSky picture TheBlueSky · Dec 28, 2012 · Viewed 10.6k times · Source

I have a Windows Phone 7 app which I'm trying to create a Windows Phone 8 version of it.

In the app I have a ResourceDictionary defined in a XAML file as:

<ResourceDictionary
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib">

    <sys:String x:Key="AppName">My App Name</sys:String>
    <!-- etc. -->

</ResourceDictionary>

This ResourceDictionary is referenced in App.xaml as:

<!--Application Resources-->
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Assets/Constants.xaml"/>
            <!-- etc. -->
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

And then the easy part of doing:

<TextBlock x:Name="ApplicationTitle" Text="{StaticResource AppName}"/>

The above works perfectly fine with Windows Phone 7, however, in Windows Phone 8 there is an additional Application.Resources item which is <myNamespace:LocalizedStrings x:Key="LocalizedStrings"/> which when I have my app does not compile as it complains about

Each dictionary entry must have an associated key.

So I changed by code to be:

<!--Application Resources-->
<Application.Resources>
    <myNamespace:LocalizedStrings x:Key="LocalizedStrings"/>
    <ResourceDictionary x:Key="MainDictionary">
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Assets/Constants.xaml"/>
            <!-- etc. -->
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Now I have another problem. My app compiles but when it runs it throws a XamlParseException:

Cannot find a Resource with the Name/Key AppName

This all happens because of LocalizedStrings resource. Can someone help in making that work?

By the way, I have the same issue with the Value Converters; if they are done differently I appreciate if someone can help in that as well.

Thanks in advance.

Answer

Paul Annetts picture Paul Annetts · Dec 29, 2012

Move the localized strings entry into the top-level application resource dictionary.

<!--Application Resources-->
<Application.Resources>
        <ResourceDictionary x:Key="MainDictionary">
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Assets/Constants.xaml"/>
                <!-- etc. -->
            </ResourceDictionary.MergedDictionaries>
            <myNamespace:LocalizedStrings x:Key="LocalizedStrings"/>
        </ResourceDictionary>
</Application.Resources>