使用XAML从嵌入式资源中显示图像的Xamarin Forms

5

我正在尝试在共享项目资源中显示和嵌入图像(如Microsoft文档这里所述)。

我创建了ImageResourceExtension,项目编译通过,但是当我启动项目时出现以下错误:

无法从程序集“Xamarin.Forms.Core,Version = 2.0.0.0”加载类型“Xamarin.Forms.Xaml.IReferenceProvider”

这是我的代码:

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;
        }
    }
}

1
你可以提供你的代码吗?你确定问题和图片有关吗? - Bruno Caceiro
如果我删除<Image />,就不会出现错误。所以我相当确定它们有关 :) 我已经将代码添加到了我的初始帖子中。谢谢。 - danbord
你能提供图片的路径吗?你的图片保存在共享项目的哪里? - Joehl
4个回答

5

你可以尝试这个方法,它对我有用

xyz.xaml.cs

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

xyz.xaml

<Image x:Name="imgName" />

希望这段代码能够帮助到您!

1

替换:

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

使用:

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

并替换:

var imageSource = ImageSource.FromResource(Source, typeof(...));

使用:

var imageSource = ImageSource.FromResource(Source);

0

不知道这个答案对你是否仍然有效,但我通常会在解决方案之外拥有一个Assets文件夹,其中包含Android特定的文件夹(drawables),iOS特定的文件夹(Resource with @2x和@3x)以及用于共享图像的Common文件夹。

在我的解决方案中,我将这些文件作为链接添加到它们应该关联的文件夹中。在Android中是在Resources/Drawable中,在iOS中是在Resource中。在这种情况下,可以跨两个平台共享Common文件,而无需物理复制它们。

作为奖励,这些Assets的更新可以在解决方案之外的文件夹中被覆盖,并且将在我的解决方案中使用,无需采取任何其他操作。


-1
如果您将图片添加到Android的drawable文件夹或iOS的Resource文件夹中,则不需要任何扩展名。您可以简单地执行以下操作:
 <Image x:Name="imgTest" Source="img.jpg" />

1
我知道这一点。重点是我想在多个项目之间共享资源,而不是在每个项目中复制文件(我觉得这很烦人)。 - danbord
1
不是对帖子的回答。 - Slipoch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接