如何在代码隐藏中绑定嵌入的图像

问题描述

我需要将图像绑定到 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);
        }
    }
}

解决方法

但是我如何在后面的代码中执行此操作,因为图像名称来自 SQLite 数据库并且图像位于 Images.MyPages 文件夹中。

根据您的描述,您想通过代码隐藏图像,图像存储在文件夹中,构建动作为嵌入式资源,对吗?

如果是,你可以看看下面的代码:

bars_string = input('Enter bars string:\n ')
digits = list(map(int,bars_string))
max_digit = max(digits)

print("+" + "-"*max_digit + "+")
for digit in digits:
  print("|" + "#"*digit + " "*(max_digit - digit) + "|")

print("+" + "-"*max_digit + "+")

按代码显示图像:

  <Image
            x:Name="image1"
            HeightRequest="200"
            WidthRequest="200" />

这是我的项目截图:

enter image description here