IgorShare Thoughts and Ideas

Consulting and Training

Archive for January 7th, 2009

WPF: Extracting BitmapImage from an attached resource in referenced assembly/library

Posted by Igor Moochnick on 01/07/2009

It was not that simple to find out what is a reference to a linked resource within an assembly. The biggest problem was to nail down the exact pack path to a resource. It becomes simple if you know the name of a specific assembly, but, in real life, the names are changing pretty often.

This is the solution to such a problem: find out what assembly your code is running in and then construct a pack path to it. Then update it with a relative resource path. Under “relative resource path” I mean the path to your resource relative to the project (.proj) file within the VS solution. For example: if you like to store your images under “ProjectFolder/Images” folder then the relative path to your resource will be  “Images/ImageName.png”.

Don’t forget that in WPF a linked resource should have a Resource build action (not Embedded Resource) !!!

Here is a procedure that does all the above and hides all the hustle:

private BitmapImage GetImage(string resourcePath)
{
    var image = new BitmapImage();

    string moduleName = this.GetType().Assembly.GetName().Name;
    string resourceLocation =
        string.Format("pack://application:,,,/{0};component/{1}", moduleName,
                      resourcePath);

    try
    {
        image.BeginInit();
        image.CacheOption = BitmapCacheOption.OnLoad;
        image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
        image.UriSource = new Uri(resourceLocation);
        image.EndInit();
    }
    catch (Exception e)
    {
        System.Diagnostics.Trace.WriteLine(e.ToString());
    }

    return image;
}
Advertisements

Posted in WPF | 1 Comment »

 
%d bloggers like this: