【发布时间】: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 中选择)
标签: c# image xaml xamarin xamarin.forms