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

.NET Maui数据绑定异常:Entry与Label无法实时更新求助

.NET Maui数据绑定:修改实体属性后控件不实时更新的解决办法

问题核心在于绑定的实体类未实现INotifyPropertyChanged接口:

  • 你的ViewModel通过[AddINotifyPropertyChangedInterface]实现了自身属性的变更通知,但绑定的CurrentCustomer.CustomerName是Customer实体的属性,而Customer类没有属性变更通知机制。
  • 修改CustomerName时,UI接收不到属性变化的通知,因此不会实时更新;导航到其他页面再返回时,页面重新执行数据绑定,才会显示最新值。

解决方案一:给Customer类添加属性变更通知(推荐)

直接给Customer类实现INotifyPropertyChanged接口,或使用和ViewModel相同的[AddINotifyPropertyChangedInterface]特性(需依赖PropertyChanged.Fody包):

[AddINotifyPropertyChangedInterface]
public class Customer
{
    public int CustomerId { get; set; }
    public string CustomerName { get; set; }
    public string CustomerAddress { get; set; }
    public string CustomerPhone { get; set; }
    public string Email { get; set; }
}

若手动实现接口:

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

public class Customer : INotifyPropertyChanged
{
    private int _customerId;
    private string _customerName;
    private string _customerAddress;
    private string _customerPhone;
    private string _email;

    public int CustomerId
    {
        get => _customerId;
        set
        {
            _customerId = value;
            OnPropertyChanged();
        }
    }

    public string CustomerName
    {
        get => _customerName;
        set
        {
            _customerName = value;
            OnPropertyChanged();
        }
    }

    public string CustomerAddress
    {
        get => _customerAddress;
        set
        {
            _customerAddress = value;
            OnPropertyChanged();
        }
    }

    public string CustomerPhone
    {
        get => _customerPhone;
        set
        {
            _customerPhone = value;
            OnPropertyChanged();
        }
    }

    public string Email
    {
        get => _email;
        set
        {
            _email = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

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

解决方案二:重新赋值CurrentCustomer(临时 workaround)

若不想修改Customer类,可在清空时重新创建CurrentCustomer实例,触发ViewModel中该属性的变更通知:

private void ClearUserInputs()
{
    // 重新实例化对象,触发ViewModel的属性变更通知
    CurrentCustomer = new Customer { CustomerName = string.Empty };
}

此方法虽能解决问题,但每次修改都需重新创建对象,灵活性和优雅度不如第一种方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 21:46:18