Reputation: 2861
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?
Upvotes: 5
Views: 7916
Reputation: 1
I managed to get this working by adding the ImageSource as an object in my View Model
public object ImageSource { get; set; }
Then populating the View Model as follows:
ImageSource = Xamarin.Forms.ImageSource.FromResource("ProjectName.Resources.Images.Image1.png", typeof(WalkthroughViewModel).GetTypeInfo().Assembly),
In the XAML, I simply referenced it as I would any other binding.
<Image Source="{Binding ImageSource}"/>
I am aware that the question doesn't necessarily use/require model-binding as you would with MVVM but I stumbled upon the answer provided above which helped me figure out the MVVM approach for anyone else who finds it useful. My particular use-case was for a CarouselView where I figured an embedded set of images would be useful.
Upvotes: 0
Reputation: 5331
@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}" />
Upvotes: 16
Reputation: 144
you can set image from xaml like <Image Source="imageName" Aspect="AspectFit" />
Make sure your image available in iOS Resources and in Android Resources -> drawable
Upvotes: -2