如何在Xamarin.Forms中使用XAML从嵌入资源设置图像

5
在代码中设置图像源并指向 PCL 项目中特定文件夹中的嵌入式图像(在此实例中为“Images”),我会这样做:
backgroundImg.Source = ImageSource.FromResource("Myapp.Images." + imageName + ".jpg");

有没有一种在XAML中实现这个的方法?
4个回答

15

@Code Pope在他的回答中是正确的,但你还需要按@Gerald Versluis的评论所述添加一个"ImageResourceExtension"。

要做到这一点,只需创建一个新文件(类)"ImageResourceExtension.cs",内容如下:

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

然后在你的 XAML 文件中添加以下代码:xmlns:local="clr-namespace:ImageResourceExtension"

<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"
         ...

现在您可以使用XAML代码访问嵌入式资源,如下所示:

现在您可以像这样使用XAML代码访问嵌入式资源:

<Image Source="{local:ImageResource MyProject.Resources.Images.Logo.png}" />

3
请使用以下代码:
<Image Source="{local:ImageResource YourMobileAppName.YouImageName.jpg}" />

了解更多信息,请点击这里


我之前尝试过这个,但是出现了“在xmlns clr-namespace中找不到类型ImageResource”的错误,导致无法构建。 - DarkW1nter
你已经将你的应用程序名称作为前缀插入到图像中了吗? - Code Pope
我已经尝试过 {local:ImageResource MyApp.Images.testImg.jpg} 和 {local:ImageResource MyApp.testImg.jpg}。 - DarkW1nter
1
@DarkW1nter,你需要实现可以在页面上找到的扩展,并将其导入到页面根目录下的“local”命名空间中。不过,你仍然需要进行调整,以使其能够接受动态图像文件名。 - Gerald Versluis

0

我通过将ImageSource作为我的视图模型中的对象添加来使其工作。

public object ImageSource { get; set; }

然后按照以下方式填充视图模型:

ImageSource = Xamarin.Forms.ImageSource.FromResource("ProjectName.Resources.Images.Image1.png", typeof(WalkthroughViewModel).GetTypeInfo().Assembly),

在XAML中,我只需像任何其他绑定一样引用它。
<Image Source="{Binding ImageSource}"/>

我知道这个问题不一定需要使用/要求模型绑定,就像MVVM一样,但我偶然发现了上面提供的答案,它帮助我找到了MVVM方法,对于其他人也可能会有用。我的特定用例是用于CarouselView,我认为嵌入式图像集将非常有用。


-2

你可以在XAML中设置图片,例如:<Image Source="imageName" Aspect="AspectFit" /> 确保你的图片在iOS资源和Android资源中都可用 -> drawable


他特别要求从共享项目中检索图像。 - Gerald Versluis

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