MAUI绑定Entry在底层值变更后不刷新问题求助
问题根源与解决方案
Entry控件未刷新的核心原因是:你的Expense类没有实现INotifyPropertyChanged接口,当CountOfReceipts属性值变更时,无法向绑定的UI控件发送属性变更通知。
为什么会这样?
你在ViewModel中使用了[ObservableProperty]特性,这会自动为Expense属性生成包含PropertyChanged事件触发逻辑的代码,所以当你替换整个Expense对象时UI会更新。但Expense对象内部的CountOfReceipts是普通属性,修改它的值时不会触发任何通知,UI控件自然不知道要刷新显示内容。
具体修复方案
有两种常用方式解决这个问题:
方案1:让Expense类手动实现INotifyPropertyChanged接口
public class Expense : INotifyPropertyChanged { public double Amount { get; set; } [PrimaryKey, AutoIncrement] public int? ID { get; set; } private int _countOfReceipts; [Ignore] public int CountOfReceipts { get => _countOfReceipts; set { if (_countOfReceipts != value) { _countOfReceipts = value; OnPropertyChanged(nameof(CountOfReceipts)); } } } [OneToMany(CascadeOperations = CascadeOperation.All)] public List<Receipt> Receipts { get; set; } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
方案2:使用CommunityToolkit.Mvvm的[ObservableProperty]特性
若项目已引入CommunityToolkit.Mvvm,可通过特性自动生成属性变更逻辑:
public partial class Expense : ObservableObject { public double Amount { get; set; } [PrimaryKey, AutoIncrement] public int? ID { get; set; } [Ignore] [ObservableProperty] private int _countOfReceipts; [OneToMany(CascadeOperations = CascadeOperation.All)] public List<Receipt> Receipts { get; set; } }
需注意让Expense继承自ObservableObject,并将类标记为partial,确保特性能自动生成带通知的CountOfReceipts公共属性。
额外说明
你提到的ChangesWereMade能正确更新并启用保存按钮,是因为这个属性在ViewModel中被[ObservableProperty]处理过,变更时会触发通知;但Entry绑定的是Expense.CountOfReceipts,这个属性的变更没有通知机制,所以UI不会同步更新。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

