Programatically Setting Image Source in Metro Style Apps with WPF

This post is for people writing “Metro Style Apps”, or apps built for Windows 8 who are trying to set the source of an image within their WPF project. It should be easy to do this but it is surprisingly tricky and took me 1.5 hours to figure out. Here’s the code:

// Usage
myImage.Source = ImageFromRelativePath(this, "relative_path_to_file_make_sure_build_set_to_content");

public static BitmapImage ImageFromRelativePath(FrameworkElement parent, string path)
{
      var uri = new Uri(parent.BaseUri, path);
      BitmapImage result = new BitmapImage();
      result.UriSource = uri;
      return result;
}

And here’s why it’s such a pain: WinRT applications need the full path to an image, they do not accept relative paths. The full path is confusing, but you can get at it if you’re in a class that extends FrameworkElement (basically any UI element) via the BaseUri property. Totally not obvious and not easy to discover!

2 thoughts on “Programatically Setting Image Source in Metro Style Apps with WPF

  1. Pingback:  Programatical… « My blog

  2. Hi there, thanks for the post. helped me really, came from wp7 developing and I have to say, microsoft what have you done to your developers!!!!!

    Greetz Soma

Leave a Reply

Your email address will not be published. Required fields are marked *