Friday, March 23, 2018

How do I display using code an image from the Assets in a UWP project?


Let us take the simple example of a button click event displaying an image stored in the project's Asset folder on the page.

At a minimum we create a UWP Blank project. Then we add a StackPanel. In the StackPanel we place two named elements, a button and an image by providing the NAME property for the controls.

Basic Page design MainPage.xaml



Add an external image to Asset folder (you could also use an existing image)

We bring in an external image into the Asset Folder using:


Since we configured a click event in the XAML, this BTN_Click event code will be present in the MainPage.xaml.cs as shown.

Add code to MainPage,xaml.cs


We create an instance of Image as a new image. The source for this image has to change from System.Uri to Windows.Foundation.Uri that UWP requires and hence the conversion. 


However, code needs fixing, and there is a fix with a link. You can safely click this to modify. This includes a new using reference (using Windows.UI.Xaml.Media.Imaging) as shown. 

The this.BaseURI is now referencing the ASSETS folder's content that we added as shown.


Build, Deploy and RUN

This completes the code and the Project builds without errors. When you run it in the Local Machine as you have done with the others you see this page.

App Display

App Display after button click




No comments: