Fka
Fka

Reputation: 6234

WPF - Uri to content images

I spent 1 hour on browsing internet and trying to find a way how to load Uri to content image and create an BitmapImage.

That is what I have:

{
    Uri x = new Uri("/Images/appbar.chevron.up.png", UriKind.Relative);
    BitmapImage bi = new BitmapImage(x);
    return x;
}

Images in Solution Explorer are just under project:

enter image description here

And each image have Build Action as Content

enter image description here

I'm recieving The given System.Uri cannot be converted into a Windows.Foundation.Uri. Please see http://go.microsoft.com/fwlink/?LinkID=215849 for details. on creating BitmapImage, but debugger showes me that Uri was created:

enter image description here

Please tell me, how can I load selected image?

Upvotes: 0

Views: 1491

Answers (2)

Rob Caplan - MSFT
Rob Caplan - MSFT

Reputation: 21919

As noted, to load the image from your app package you'll use the ms-appx protocol. See the URI schemes documentation on MSDN

Uri x = new Uri("ms-appx:///Images/appbar.chevron.up.png");
BitmapImage bi = new BitmapImage(x);

Then you'll want to return the BitmapImage rather than the URI to your caller:

return bi; // not: return x;

Or set it on an Image control. The BitmapImage is just data and doesn't show up on its own.

img.SetSource(bi);

Where img is created in your Xaml:

Guessing from the names of the images you are trying to set them in appbar buttons. For that you can use the Segoe UI Symbol font instead of loading images:

<AppBarButton>
    <AppBarButton.Icon>
        <FontIcon FontFamily="Segoe UI Symbol" Glyph="&#57361;"/>
    </AppBarButton.Icon>
</AppBarButton>
<AppBarButton>
    <AppBarButton.Icon>
        <FontIcon FontFamily="Segoe UI Symbol" Glyph="&#57360;"/>
    </AppBarButton.Icon>
</AppBarButton>

Or if you want to set AppBarButtons to images in xaml:

<AppBarButton>
    <AppBarButton.Icon>
        <BitmapIcon UriSource="Images/appbar.chevron.up.png"/>
    </AppBarButton.Icon>
</AppBarButton>
<AppBarButton>
    <AppBarButton.Icon>
        <BitmapIcon UriSource="Images/appbar.chevron.down.png"/>
    </AppBarButton.Icon>
</AppBarButton>

Upvotes: 1

Mike Strobel
Mike Strobel

Reputation: 25623

I don't know exactly how content and resources work in WinRT, but in WPF, "Content" items must be copied to the output directory. They get added to the manifest, but the files themselves are not embedded.

If you want to embed the file, use a build action of "Resource" (it's possible that WinRT does not even support "Content"--I have never used it). It also appears that you need to create an Absolute URI with ms-appx: scheme.

Upvotes: 0

Related Questions