You need to enable JavaScript to run this app. 使用FreshMvvm框架向Firebase上传图片时Icon.Source报错如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

使用FreshMvvm框架向Firebase上传图片时Icon.Source报错如何解决?

问题根因
  • 你的ViewModel中Icon属性定义为string类型,不存在Source属性,直接操作Icon.Source属于非法调用,是触发报错的直接原因
  • Image控件的Source属性本身支持绑定ImageSource、string(本地/网络路径)、Stream等类型,不需要通过操作视图控件的方式赋值
解决方案

完全不需要在视图层写逻辑,也不需要用x:Name引用控件,只需修改ViewModel的代码即可:

  1. 调整Icon属性的类型为ImageSource
  2. 直接给Icon属性赋值选中的图片流,不需要访问Source属性
  3. 如需后续上传到Firebase,可在ViewModel中私有存储选中的图片文件/流,上传逻辑直接调用该存储对象即可

修正后的ViewModel代码

// 新增私有字段存储选中的图片文件,供后续上传Firebase使用
private MediaFile _selectedImageFile;
private ImageSource _icon;
public ImageSource Icon
{
    get => _icon;
    set
    {
        _icon = value;
        RaisePropertyChanged();
    }
}

public ICommand ImageDataCommand => new Command(async (s) => await InsertImage(s));

private async Task InsertImage(object s)
{
    await CrossMedia.Current.Initialize();
    try
    {
        var file = await CrossMedia.Current.PickPhotoAsync(new PickMediaOptions()
        {
            PhotoSize = PhotoSize.Medium
        });
        if (file == null)
            return;
        
        // 存储选中的文件,后续上传Firebase时直接调用_selectedImageFile.GetStream()即可
        _selectedImageFile = file;
        // 直接给Icon赋值,无需访问Source属性
        Icon = ImageSource.FromStream(() =>
        {
            var imageStream = file.GetStream();
            return imageStream;
        });
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex);
    }
}
Firebase上传补充说明

后续需要上传图片时,直接读取_selectedImageFile的流即可,示例逻辑:

private async Task UploadToFirebase()
{
    if(_selectedImageFile == null) return;
    using var stream = _selectedImageFile.GetStream();
    // 此处写Firebase上传逻辑,直接使用stream对象上传即可
    // 例:await firebaseStorage.Child("images/xxx.jpg").PutAsync(stream);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 04:30:04