How to reference image source files that are packaged with my metro style app?

Viewed 19502

I have a .png file as a content of my application. When I bind it in xaml like this

<ImageBrush x:Key="BtnBackImageBrush" ImageSource="/Assets/Images/back.png" />

everything ok.

I read this article and when I try to get access to this .png programmatically I get an error.

Code I use:

Uri baseUri = new Uri("ms:appx");
Image img = new Image();
img.Source = new BitmapImage(new Uri(baseUri, "/Assets/Images/back.png"));
img.ImageFailed += (sender, args) => new MessageDialog("Error").ShowAsync();

And my question is how to reference image source files that are packaged with my metro style app?

Thanks for advices.

UPDATE: I found answer! We need set baseUri using parent FrameworkElement instead of setting it manually. For example:

// 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;
}

Thanks for this article.

2 Answers
Related