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

MAUI页面初始化时ViewModel获数据但UI无法更新的问题求助

MAUI UI不更新问题解决方案

问题原因

你当前使用的List<PatientModel>不支持集合元素变更通知。虽然[ObservableProperty]会在整个Patients对象被替换时触发属性变更通知,但往现有List中添加/删除元素时,List本身不会向UI发送更新信号,导致UI无法感知到集合内容变化。

解决方案

将集合类型替换为ObservableCollection<PatientModel>——这个类型实现了INotifyCollectionChanged接口,能在集合元素增删、排序等操作时自动通知UI更新。

修改后的ViewModel代码

using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace FollowUpApp.ViewModels;

public partial class RelatedPersonListViewModel : ObservableObject
{
    [ObservableProperty]
    private ObservableCollection<PatientModel> _patients = []; 

    [RelayCommand]
    private async Task Appearing()
    {
        Patients.Add(new PatientModel() { PatientID = "001", PatientName = "ZhangSan", Sex = "F", Age = "36" });
        Patients.Add(new PatientModel() { PatientID = "002", PatientName = "LiSi", Sex = "M", Age = "38" });

        await Task.FromResult(0);
    }
}

额外检查点

  • 确保项目已正确引用CommunityToolkit.Mvvm NuGet包(你已在使用ObservableObject和RelayCommand,此步骤大概率已完成)
  • 确认XAML中BindableLayout.ItemsSource="{Binding Patients}"的绑定路径无拼写错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 07:43:17