.NET MAUI绑定值变更后Entry控件值不更新问题求助
问题根源
- Patient类无属性变更通知:
Patient的Id、Lastname是普通自动属性,修改时不会触发PropertyChanged事件,UI绑定无法感知数据变化。 - ViewModel属性未实现可观察:
HomePageViewModel中的MyPatient是普通属性,即使替换对象也无法通知UI;同时修改对象内部属性时,因Patient无通知机制,UI也不会更新。 - ImportPage导航逻辑混乱:
btnCancel_Clicked中先跳转HomePage再执行返回操作,导致导航栈异常,参数传递失效。
解决步骤
1. 改造Patient类实现属性变更通知
借助CommunityToolkit.Mvvm的ObservableObject和[ObservableProperty]特性,自动生成带变更通知的属性:
using CommunityToolkit.Mvvm.ComponentModel; namespace Aequus.CoreBusiness { public partial class Patient : ObservableObject { [ObservableProperty] private int id; [ObservableProperty] private string lastname = string.Empty; [ObservableProperty] private string firstname = string.Empty; public override string ToString() { return Lastname + ", " + Firstname; } } }
2. 修正ViewModel的MyPatient属性
将MyPatient改为可观察属性,确保对象替换或内部属性修改时能通知UI:
using Aequus.CoreBusiness; using Aequus.UseCases.Interfaces; using CommunityToolkit.Mvvm.ComponentModel; using DicomObjects; using DicomObjects.Enums; namespace Aequus.Maui.ViewModels { public partial class HomePageViewModel : ObservableObject, IQueryAttributable { [ObservableProperty] private Patient? myPatient; public ILoadPatientUseCase LoadPatientUseCase { get; } private DicomImage? currentDicomImage = null; public HomePageViewModel(ILoadPatientUseCase loadPatientUseCase) { LoadPatientUseCase = loadPatientUseCase; LoadPatientAsync(); } public async Task LoadPatientAsync() { MyPatient = await LoadPatientUseCase.ExecuteAsync(); } public void ApplyQueryAttributes(IDictionary<string, object> query) { if (query.TryGetValue("ReturnedObject", out var obj)) { MyPatient.Lastname = "Peters"; MyPatient.Id = 2; Application.Current.MainPage.DisplayAlert("MESSAGE", MyPatient.Lastname, "OK"); } } } }
3. 修复ImportPage导航逻辑
删除重复导航操作,直接返回上一页并传递参数:
namespace Aequus.Maui.Views; using DicomObjects; public partial class ImportPage : ContentPage { public DicomImage? currentDicomImage; public ImportPage() { InitializeComponent(); } private async void btnImport_Clicked(object sender, EventArgs e) { } private async void btnCancel_Clicked(object sender, EventArgs e) { var navigationParameter = new Dictionary<string, object> { { "ReturnedObject", currentDicomImage } }; await Shell.Current.GoToAsync("..", navigationParameter); } }
4. 验证绑定逻辑
XAML中的绑定无需修改,因[ObservableProperty]生成的属性名与原MyPatient、Id、Lastname一致,修改后UI会自动同步数据变化。
内容的提问来源于stack exchange,提问作者Sabre
相关产品推荐
相关产品推荐

