How to set an image from Embedded resource using XAML in Xamarin.Forms
When setting an image source in code and pointing towards an embedded image in a specific folder in the PCL project ('Images' in this instance) I would do this:
backgroundImg.Source = ImageSource.FromResource("Myapp.Images." + imageName + ".jpg");
Is there a way to do this in XAML?
@Code Pope is correct in his answer, but you also need to add an "ImageResourceExtension" as noted in the comments by @Gerald Versluis.
To do that just create a new file (class) "ImageResourceExtension.cs" like this:
using System;
using System.Reflection;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace ImageResourceExtension
{
[ContentProperty (nameof(Source))]
class ImageResourceExtension : IMarkupExtension
{
public string Source { get; set; }
public object ProvideValue(IServiceProvider serviceProvider)
{
if (Source == null)
{
return null;
}
var imageSource = ImageSource.FromResource(Source, typeof(ImageResourceExtension).GetTypeInfo().Assembly);
return imageSource;
}
}
}
Then add xmlns:local="clr-namespace:ImageResourceExtension"
to your xaml file like this:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ImageResourceExtension"
...
Now you can access an embedded resource using xaml code like this:
<Image Source="{local:ImageResource MyProject.Resources.Images.Logo.png}" />
Use the following code:
<Image Source="{local:ImageResource YourMobileAppName.YouImageName.jpg}" />
For more info, read here