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

.NET 8 MAUI中资源图片加载到数据模型的空引用异常问题

.NET 8 MAUI 自定义复选框图片切换问题解决方案

核心问题排查

你遇到的System.NullReferenceException,优先排查checkItem实例是否未初始化——如果checkItem本身是null,哪怕图片加载正常,赋值时也会抛出空引用异常。

修正步骤

1. 确保checkItem已实例化

在赋值前必须创建模型实例,比如:

// 假设你的模型类名为CheckItem
var checkItem = new CheckItem();

2. 简化图片赋值代码

ImageSource.FromResource返回的StreamImageSource是ImageSource的派生类,直接赋值给ImageSource类型属性完全兼容,无需额外变量或as转换:

checkItem.selectedImage = item.isActive 
    ? ImageSource.FromResource("Resources/Images/greencheck.png") 
    : ImageSource.FromResource("Resources/Images/greenchecknotselected.png");

3. (可选)实现UI自动刷新

如果需要图片切换时UI自动更新,模型需实现INotifyPropertyChanged接口:

using System.ComponentModel;
using System.Runtime.CompilerServices;

public class CheckItem : INotifyPropertyChanged
{
    [Ignore]
    private ImageSource _selectedImage;
    
    public ImageSource selectedImage 
    { 
        get => _selectedImage; 
        set 
        {
            if (_selectedImage != value)
            {
                _selectedImage = value;
                OnPropertyChanged();
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

4. 验证资源配置(兜底排查)

确认图片文件的生成操作已设置为Embedded resource:

  • 在解决方案资源管理器中右键图片文件 → 属性
  • 将“生成操作”改为Embedded resource

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 21:12:34