嵌入的图像不显示

Embedded images not showing

这是我在可移植项目中的页面

    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:b="clr-namespace:Corcav.Behaviors;assembly=Corcav.Behaviors"
                 xmlns:local="clr-namespace:MyMobileApp;assembly=MyMobileApp"
                 x:Class="MyMobileApp.MainPage"
                 x:Name="MainPage">

      <Image Source="{local:ImageResource myimage.jpg}" />

这是我在同一便携式项目中的 ImageResourceExtension

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

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

            var imageSource = ImageSource.FromResource(Source);

            return imageSource;
        }
    }
}

我尝试将 myimage.jpg 添加到项目的根目录和 Resources 文件夹中,但没有显示图像。

调试时我看到返回的 imageSource 是 Xamarin.Forms.StreamImageSource 类型。如何检查是否真的找到了?

谁能找出这里的错误?

你能再解释一下扩展的意图吗?假设您将图像放在正确的文件夹中('Resources' 在 iOS 上,'Resources/Drawable' 在 Android 上),那么您在 XAML 中只需要:

<Image Source="FeaturedAreaMockup.jpg" />

这会在适当的文件夹中找到图像并显示它们 - 你为什么不这样做呢?扩展的意义何在?

要阅读 assets/resources 文件夹,您需要使用:

ImageSource.FromFile("myimage.jpg");'

ImageSource.FromResource 使用包含的图像 EmbeddedResource

更多信息:https://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/images/

正确的XAML是将应用程序名称添加到源中。

<Image Source="{local:ImageResource MyMobileApp.myimage.jpg}" />

默认情况下,图像将具有构建操作:None;这需要设置为 Build Action: EmbeddedResource。 右键单击图像 > 属性 > 设置 [Build Action: EmbeddedResource] []1