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

.NET MAUI转换器在值变更后无响应/不转换问题求助

.NET MAUI中IsCorrect变更后UI未同步更新的解决方案

问题根源和转换器无关,是因为Answer类没有实现INotifyPropertyChanged接口。当IsCorrect属性值修改时,无法向绑定的UI控件发送属性变更通知,导致UI不会自动刷新。

解决步骤:

  • 让Answer类实现INotifyPropertyChanged接口,添加属性变更事件和触发通知的通用方法
  • 修改需要UI同步的属性(如IsCorrect、IsSelected)的setter逻辑,在值变更时触发通知

修改后的Answer类代码:

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

public class Answer : INotifyPropertyChanged
{
    [Key]
    public int AnswerId { get; set; }
    public int QuestionId { get; set; }
    public string Content { get; set; }
    
    private bool _isCorrect;
    public bool IsCorrect
    {
        get => _isCorrect;
        set
        {
            if (_isCorrect != value)
            {
                _isCorrect = value;
                OnPropertyChanged();
            }
        }
    }
    
    public int? Points { get; set; }
    
    [NotMapped]
    private bool _isSelected;
    public bool IsSelected
    {
        get => _isSelected;
        set
        {
            if (_isSelected != value)
            {
                _isSelected = value;
                OnPropertyChanged();
            }
        }
    }

    public event PropertyChangedEventHandler? PropertyChanged;

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

验证说明:

  • 转换器本身逻辑没有问题,只要IsCorrect属性变更时能触发PropertyChanged事件,UI就会自动调用转换器更新Label的Text和TextColor
  • 确保页面的BindingContext正确指向Answer类的实例

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 16:03:30