如何在后面的代码中绑定嵌入的图像
Posted
技术标签:
【中文标题】如何在后面的代码中绑定嵌入的图像【英文标题】:How to Bind Embedded Image in Code Behind 【发布时间】:2021-05-10 20:19:52 【问题描述】:我需要将图像绑定到 Xamarin 中的 <Image>
控件。
我使用找到的代码 here,我可以通过在 XAML 标记中硬编码图像名称来做到这一点。
但是由于图像名称来自 SQLite 数据库并且图像位于 Images.MyPages
文件夹中,我该如何在后面的代码中执行此操作。
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:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="SApp.Views.SPages"
xmlns:local="clr-namespace:SApp.MarkupExtensions">
<ContentPage.Content>
<StackLayout>
<Image Source="local:QEmbeddedImage ResourceId=SApp.Images.SPages.page0.jpg" x:Name="pageImage" Aspect="AspectFill"></Image>
</StackLayout>
</ContentPage.Content>
</ContentPage>
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using SApp.MarkupExtensions;
namespace SApp.Views
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SPages : ContentPage
public SPages()
InitializeComponent();
EmbeddedImage
实现:
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace SApp.MarkupExtensions
[ContentProperty("ResourceId")]
public class QEmbeddedImage : IMarkupExtension
public string ResourceId get; set;
public object ProvideValue(IServiceProvider serviceProvider)
if (string.IsNullOrWhiteSpace(ResourceId))
return null;
return ImageSource.FromResource(ResourceId);
【问题讨论】:
如果图像存储在文件夹中,则应通过文件路径访问,而不是作为资源访问 @Jason 作为 EmbeddedResource 添加(在 BuildAction 中选择) 【参考方案1】:但是我如何在后面的代码中执行此操作,因为图像名称来自 SQLite 数据库并且图像位于 Images.MyPages 文件夹中。
根据您的描述,您想通过代码显示图像,图像存储在文件夹中,将操作构建为嵌入式资源,对吗?
如果是,你可以看看下面的代码:
<Image
x:Name="image1"
HeightRequest="200"
WidthRequest="200" />
通过后面的代码显示图片:
public Page1()
InitializeComponent();
image1.Source = ImageSource.FromResource("FormsSample.images.image2.png", typeof(Page1).GetTypeInfo().Assembly);
这是我的项目截图:
【讨论】:
以上是关于如何在后面的代码中绑定嵌入的图像的主要内容,如果未能解决你的问题,请参考以下文章