Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 613
azhidkov Avatar asked Aug 05 '12 08:08

azhidkov


2 Answers

new Uri("ms:appx");

I think that's the source of the original problem. The scheme is ms-appx not ms:appx

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're really trying to scope something like its parent - even if both work, the latter is probably may be clearer to the reader of your intent (assuming that's your intent).

like image 109
Howard Kapustein Avatar answered Nov 19 '22 10:11

Howard Kapustein


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;
}
like image 22
Sajid Avatar answered Nov 19 '22 10:11

Sajid