/ Silverlight

Tips and Tricks: Simplifying Resource References in WPF and Silverlight

Consider the following piece of XAML:

<Image Source="/MyCompany.MyProduct.Framework;component/CommonResources/Assets/Logo.png" />

If you ever had to write this kind of URIs you probably know that it is quite painful and error prone. So I wanted to share a simple trick that I use to simplify such resource references.
Here it is:

<Image Source="{commonAssets:Logo__png}" />

Or, if you want to access the resource in your C# code (in code-behind or whatever):

Uri myLogoUri = new Logo__png().Uri; 
// OR... 
Stream myLogoStream = new Logo__png().Stream.

It looks simpler and it allows a strongly typed access to the resource, in a way similar to the classic .NET ".resx" resources, where there is an auto generated class with strongly typed properties for accessing individual resources.

How It Works

You might have already guessed it. You need to create a class for each resource that you want to access in such manner:

wpf-res-ref-1

The name of the class must be the same as the name of the resource plus the extension separated by “__”.

The class itself is trivial:

public class Logo__png : ResourceAccessor 
{ 
}

All the magic is happening in its base class – ResourceAccessor, which does two simple things:

  • First, it builds a URI using the name of the assembly where the class is located, the namespace the class is part of and the name of the class itself. So, in the example above, the name of the assembly is MyCompany.MyProduct.Framework, the namespace is MyCompany.MyProduct.Framework.CommonResources.Assets and the name of the class is Logo__png. So, you get the idea. By applying some string replacement and concatenation magic we get our URI:

    /MyCompany.MyProduct.Framework;component/CommonResources/Assets/Logo.png.

  • The second thing that it does is it inherits from MarkupExtension and implements its ProvideValue method, where it returns the URI that it has built, which makes the following syntax work:

    <Image Source="{commonAssets:Logo__png}" />
    

This is basically it. Below is the complete source code of the ResourceAccessor class:

Pavlo Glazkov

Pavlo Glazkov

Programmer. Full stack, with a focus on UI. JavaScript/TypeScript, Angular, Node.js, .NET

Read More