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

Xamarin Forms 4.2视图与ViewModel数据绑定值不显示问题排查

问题根源与解决方案

你遇到的这个问题其实很典型——Xamarin.Forms的数据绑定只能作用于属性(Property),而不能直接绑定字段(Field)。

看你的Upload类代码:

public class Upload
{
    public string Id; // 这是一个字段,不是属性
}

这里的Id是字段,没有get/set访问器,Xamarin.Forms的绑定引擎无法识别并读取它的值,哪怕你能在断点里看到Id有值,UI也没法获取到这个数据。

修复步骤

只需要把Upload类里的Id字段改成带访问器的属性即可:

public class Upload
{
    // 改为带getter和setter的属性
    public string Id { get; set; }
}

额外补充(可选)

如果后续你需要在Id的值变化时自动更新UI,还需要让Upload类实现INotifyPropertyChanged接口,触发属性变更通知:

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

public class Upload : INotifyPropertyChanged
{
    private string _id;
    public string Id
    {
        get => _id;
        set
        {
            if (_id != value)
            {
                _id = value;
                OnPropertyChanged();
            }
        }
    }

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

你的其他代码逻辑都是正确的:BindingContext设置无误,ViewModel的Upload实例也正确传递了,只要把字段改成属性,Label就能正常显示Upload.Id的值了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:39:39