首页 > 解决方案 > Xamarin Forms 使用 XAML 显示来自嵌入式资源的图像

问题描述

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

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

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

这是我的代码:

主页.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>

嵌入式图像.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;
        }
    }
}

标签: xamarinxamarin.forms

解决方案


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

xyz.xaml.cs

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

xyz.xaml

<Image x:Name="imgName" />

希望这段代码对你有帮助!!


推荐阅读