Thursday, March 22, 2018

Adding an image in the Asset folder to a UWP project's page

You may need to display an image stored in the asset of your UWP project from another control's event handler.

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.

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.

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.

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
It is important to note that the Visual Studio's debugging, intellisense, code completion and code hints should be used effectively as it is not possible to remember all the details of Windows.Foundation classes.

No comments: Protection Status