How do I link to source image files that are packaged in my metro style app?

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

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

everything is fine.

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

The code I'm using is:

 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 do I reference the source image files that are packaged into my metro style app?

Thanks for the tips.

UPDATE: I found the answer! We need to set baseUri using the 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; } 

Thank you for the article .

+7
source share
2 answers

new Uri ("ms: appx");

I think the source of the original problem. Ms-appx not ms: appx schema

Bad URI: ms:appx://Assets/Images/back.png
Good URI: ms-appx://Assets/Images/back.png

But using FrameworkElement is not a bad idea if you are really trying to embrace something like your parent - even if both work, the latter could probably be clearer to the reader of your intention (assuming that you intend).

+9
source

Yes, you are right, this is the answer to your question.

 img.Source = ImageFromRelativePath(this, "Assets/Images/back.png"); public static BitmapImage ImageFromRelativePath(FrameworkElement parent, string path) { var uri = new Uri(parent.BaseUri, path); BitmapImage bmp = new BitmapImage(); bmp.UriSource = uri; return bmp; } 
+6
source

All Articles