You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# Maui项目中SQLite存储图片资源URI无法显示问题求助

解决MAUI中嵌入资源图片从数据库读取后无法显示的问题

1. 确认图片的Build Action设置

首先必须确保图片文件的Build Action配置正确:

  • 若使用ImageSource.FromResource加载:将Build Action设为EmbeddedResource
  • 若直接使用MAUI原生资源引用:将Build Action设为MauiImage(推荐方案)

配置方式:右键图片文件 → 属性 → 找到Build Action选项修改。

2. 修正转换器逻辑

你的转换器缺少程序集指定,这是资源加载失败的核心原因之一。修改转换器代码,明确指定资源所在程序集,并增加调试验证:

using System.Reflection;
using Microsoft.Maui.Controls;

public class ImagePathConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is not string imagePath || string.IsNullOrWhiteSpace(imagePath))
            return null;

        // 获取当前程序集(若资源在其他程序集,替换为对应Assembly实例)
        var assembly = Assembly.GetExecutingAssembly();
        
        // 调试用:验证资源是否存在,输出日志便于排查
        if (!assembly.GetManifestResourceNames().Contains(imagePath))
        {
            System.Diagnostics.Debug.WriteLine($"资源不存在:{imagePath}");
            return null;
        }

        return ImageSource.FromResource(imagePath, assembly);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

3. 数据库存储正确的资源字符串格式

根据Build Action的不同,存储的字符串格式分为两种:

情况一:Build Action为EmbeddedResource

存储的字符串必须是程序集全名 + 资源的命名空间路径,格式示例:

[你的程序集名称].[资源文件夹层级(用点分隔)].[图片文件名]

比如程序集名为MyMauiApp,图片位于Resources/Images/Thumb/adv1.jpg,则存储的字符串应为:

MyMauiApp.Resources.Images.Thumb.adv1.jpg

注意:路径大小写必须和文件系统完全一致,MAUI对嵌入资源的大小写敏感。

情况二:Build Action为MauiImage

此时无需使用转换器,直接绑定相对路径即可,存储的字符串格式为:

Resources/Images/Thumb/adv1.jpg

对应的XAML可简化为:

<Image Source="{Binding Image}" WidthRequest="66" />

4. 调试排查技巧

若仍无法显示,可通过以下方式定位问题:

  • 在转换器中打印当前程序集的所有资源名称,确认你的存储路径是否匹配:
    var allResources = assembly.GetManifestResourceNames();
    foreach (var res in allResources)
    {
        System.Diagnostics.Debug.WriteLine(res);
    }
    
  • 检查数据库中存储的字符串是否与调试输出的资源名称完全一致。

内容的提问来源于stack exchange,提问作者Picco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 03:37:32