Create application resources in windows phone.

Today I’ll show you how to share resources across Windows Phone application.
Maybe it’s not the best approach, but it’s the basics.

First of all let’s review the resource dictionaries hierarchy in Windows Phone application.

All visual elements have their own resource dictionary.

The algorithm of finding appropriate resource is the following:
check the current element dictionary then it’s parent then it’s parent and it’s parent depend on how many parents it’s have of course:) The last place where it checks is App.xaml file. I mean the resource dictionary defined in application object. Let’s call it top-level resource dictionary.
If you define the top-level resources then override them in control or page, this item will use the dictionary which was defined inside it.
By the way, the pre-defined WindowsPhone StaticResources like PhoneForegroundBrush are injected in the application when it starts.

Let’s see how to define top-level resources in example.
Now We’ll place our ResourceDictionary to the right place. The App.xaml file will look like this:


<Application ...>

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Themes/Generic.xaml"/>
            </ResourceDictionary.MergedDictionaries>
     </ResourceDictionary>
    </Application.Resources>

   ...
<!--Other elements are here-->
</Application>

We can add to the top level resource dictionary styles which we need to access around the application.
Can be background colors, brushes, gradients or converters. In our example, let’s place BitmapImage with Uri.
Our resource dictionary will look like this:

<ResourceDictionary
    ...>
    
    <BitmapImage x:Key="SharedImageSource" UriSource="../Images/SharedImage.png" />
   <!--Other styles are here-->

</ResourceDictionary>

Now you can use all you’ve added to your top-level resource dictionary across the application.

<ImageBrush ImageSource="{StaticResource SharedImageSource}"/>

Thank you for reading!

Leave a comment