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

19,480

Solution 1

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).

Solution 2

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;
}
Share:
19,480
azhidkov
Author by

azhidkov

Updated on June 17, 2022

Comments

  • azhidkov
    azhidkov almost 2 years

    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.