Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Forms Display image from Embedded resource using XAML

Tags:

I'm trying to display and embedded image in a shared project resource (as explained here on microsoft documentation).

I created the ImageResourceExtension, the project compiles, but I get the following error when I start the project :

Could not load type 'Xamarin.Forms.Xaml.IReferenceProvider' from assembly 'Xamarin.Forms.Core, Version=2.0.0.0

Here's my code :

MainPage.xaml

<?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:App1"
             x:Class="App1.MainPage">

    <StackLayout>

        <Image x:Name="imgTest" Source="{local:ImageResource img.jpg}" />

    </StackLayout>

</ContentPage>

EmbeddedImage.cs

namespace App1
{
    [ContentProperty(nameof(Source))]
    public class ImageResourceExtension : IMarkupExtension
    {
        public string Source { get; set; }

        public object ProvideValue(IServiceProvider serviceProvider)
        {
            if (Source == null)
                return null;

            // Do your translation lookup here, using whatever method you require
            var imageSource = ImageSource.FromResource(Source, typeof(ImageResourceExtension).GetTypeInfo().Assembly);

            return imageSource;
        }
    }
}
like image 917
danbord Avatar asked Oct 13 '18 14:10

danbord


People also ask

How to use image source in Xamarin forms?

Android - Place images in the Resources/drawable directory with Build Action: AndroidResource. High- and low-DPI versions of an image can also be supplied (in appropriately named Resources subdirectories such as drawable-ldpi, drawable-hdpi, and drawable-xhdpi).

How to bind image in Xamarin forms?

In Xamarin. Forms SfAvatarView, you can set the key for ImageSource by using ResourceDictionary and bind image from ViewModel to ImageSource. An ImageSource instance, can be either File, Uri or Resource, which sets the image to display.

How do I use xamarin community toolkit?

Setup Xamarin Community ToolkitOpen an existing project, or create a new project using the Blank Forms App template. In the Solution Explorer panel, right click on your project name and select Manage NuGet Packages. Search for Xamarin. CommunityToolkit, and choose the desired NuGet Package from the list.


1 Answers

You can try this, it works for me

xyz.xaml.cs

imgName.Source = ImageSource.FromResource("ProjectName.Images.backicon.png");

xyz.xaml

<Image x:Name="imgName" />

Hope this code helps you!!

like image 125
Nitika Chopra Avatar answered Oct 27 '22 00:10

Nitika Chopra