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

.NET MAUI中XAML绑定模型后UI不更新的问题求助

解决方案

你的问题主要由几个代码错误导致,修正后即可实现UI正常更新:

1. 修复QueryProperty属性的错误用法

QueryProperty的第一个参数必须是ViewModel中对应属性的名称,而非Model的类型名。原代码错误引用了Model.LoginResult,导致MAUI无法正确将导航参数绑定到ViewModel的LoginResult属性。

修改ViewModel顶部的特性:

// 错误写法
// [QueryProperty(nameof(Model.LoginResult), "LoginResult")]

// 正确写法
[QueryProperty(nameof(LoginResult), "LoginResult")]

2. 使用注入的Service实例而非静态方法

你已经通过构造函数注入了MealPacService,但在GetDataForView中错误调用了静态方法Services.MealPacService.GetUser,这会导致依赖注入失效,可能无法正确获取数据。

修改GetDataForView方法:

[RelayCommand]
async Task GetDataForView()
{
    try
    {
        if (loginResult != null)
        {
            // 使用注入的实例而非静态方法
            var incomingUser = await mealPacService.GetUser(loginResult.Reference, loginResult.OrganisationId);
            if (incomingUser != null)
            {
                user = incomingUser;
            }
        }
    }
    catch (Exception)
    {
        throw;
    }
}

3. 异步调用命令时使用await

在OnLoginResultChanged中调用异步命令时,建议使用await确保异步操作完成,避免潜在的上下文问题或UI更新延迟:

partial async void OnLoginResultChanged(LoginResult value)
{
    await GetDataForViewCommand.ExecuteAsync(null);
}

验证要点

  • 确保导航跳转时传递的参数名称为"LoginResult",与QueryProperty的第二个参数完全一致。
  • 确认MealPacService.GetUser方法能正确返回User对象(可通过断点调试验证)。

修正后,当LoginResult被导航参数赋值时,OnLoginResultChanged会触发并调用GetDataForView获取用户数据,由于User是[ObservableProperty]标记的属性,属性变更会自动通知UI刷新,XAML中的{Binding User.Name}就能正确显示内容。

内容的提问来源于stack exchange,提问作者Johan van der Merwe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 08:25:21