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

MAUI中传递Query参数为空问题排查

MAUI Shell Query参数接收为空的问题解决

核心问题:构造函数调用时机过早

QueryProperty的赋值逻辑是在ViewModel实例化之后执行的,你在LocationModel的构造函数里打印RestaurantId,此时参数还没被赋值,所以输出为空。

修复步骤

1. 监听属性变化获取参数

利用ObservableProperty的特性,通过属性变更回调在参数真正赋值后处理:

[QueryProperty("RestaurantId", "restaurantId")]
internal partial class LocationModel : ObservableObject
{
    [ObservableProperty]
    public string restaurantId;

    partial void OnRestaurantIdChanged(string value)
    {
        // 此处可获取到正确的参数值
        Console.WriteLine(RestaurantId);
    }
}

2. 确认页面与ViewModel的绑定关系

确保LocationPage的BindingContext正确关联到LocationModel:

  • XAML方式:
<ContentPage.BindingContext>
    <local:LocationModel />
</ContentPage.BindingContext>
  • 代码后台方式:
public LocationPage()
{
    InitializeComponent();
    BindingContext = new LocationModel();
}

3. 可选:用字典形式显式传递参数

如果字符串拼接式传递有隐式问题,可改用字典传递参数:

await Shell.Current.GoToAsync("location", new Dictionary<string, object>
{
    { "restaurantId", restaurantId }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 13:11:13