Thursday, May 18, 2017

Xamarin Forms: Referencing an image resource from XAML

Stolen shamelessly from Charles Petzold's superb book "Creating Mobile Apps with Xamarin.Forms" - First Edition Chapter 13. Available for free from Xamarin.com

Xamarin Forms does not contain a mechanism for referencing an embedding image in XAML. Here is a fairly simple markup extension that fixes that problem. Hopefully the Xamarin people will embed this into Xamarin.Forms in an upcoming release.

Start a new Xamarin.Forms PCL project and call it ImageXAML. File -> New -> Project...

Don't forget to select PCL after clicking [OK]
Now add a new class to ImageXAML (Portable) called ImageResourceExtension. Edit the class to look like this.

using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace ImageXAML
{
    [ContentProperty ("Source")]
    class ImageResourceExtension : IMarkupExtension
    {
        public string Source { get; set; }
        public object ProvideValue (IServiceProvider serviceProvider)
        {
            if (Source == null) return null;
            return ImageSource.FromResource(Source);
        }
    }
}

This class implements IMarkupExtension which exposes a Source property and a ProvideValue method. You populate the source property with a resource reference in the XAML and the framework uses ProvideValue to get the image resource. The ContentProperty decoration allows you to simplify your XAML because it knows the Content property is called Source.

This example assumes that Source is a resource but it would be easy to write versions that assume it is a URL, etc.

Add a new folder to ImageXAML (portable) called Images and add jpg, bmp, or png image to it. You must set the Build Action to Embedded Resource. If you forget to do this the call to FromResource() will not return anything and will not throw an error.

Your Solution Explorer will look something like this...


Now open MainPage.xaml and replace the label with an image tag. Note the format of the embedded resource reference is <Namespace>.<Path>.<FileName>


<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:ImageXAML"
             x:Class="ImageXAML.MainPage">

    <Image Source="{local:ImageResource ImageXAML.Images.Happy.jpg}"></Image>

</ContentPage>

Run the project. You will see something like this...


No comments:

Post a Comment