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

.NET MAUI如何在ViewModel中直接接收查询参数?

直接在ViewModel中接收MAUI导航查询参数的实现方案

问题背景

目前通过页面后台中转传递导航查询参数,希望简化为ViewModel直接接收,参考相关示例但尝试时参数始终为null。

实现步骤及代码修改

1. 改造ViewModel,添加查询属性与自动加载逻辑

给ViewModel添加[QueryProperty]特性,利用属性变更触发数据加载(需确保BaseViewModel已继承INotifyPropertyChanged):

public partial class MyPageViewModel : BaseViewModel
{
    private readonly IMyService _myService;
    private string _id;

    // 绑定导航查询参数:第一个参数是ViewModel属性名,第二个是URL中的查询参数名
    [QueryProperty(nameof(Id), nameof(Id))]
    public string Id
    {
        get => _id;
        set
        {
            // SetProperty是BaseViewModel中封装的属性变更方法,会触发INotifyPropertyChanged
            if (SetProperty(ref _id, value))
            {
                // 属性值更新后自动加载数据
                _ = LoadDataAsync();
            }
        }
    }

    public MyPageViewModel(IMyService myService)
    {
        _myService = myService;
    }

    private async Task LoadDataAsync()
    {
        if (string.IsNullOrEmpty(Id)) return;
        // 执行业务数据获取逻辑
        var data = await _myService.Get(Id);
    }
}

2. 简化页面后台代码

移除页面中的查询属性标记和参数传递逻辑,仅保留ViewModel绑定:

public partial class MyPage : ContentPage
{
    public MyPage(MyPageViewModel vm)
    {
        InitializeComponent();
        BindingContext = vm;
    }
}

关键注意事项

  • 导航时的查询参数名必须与[QueryProperty]特性的第二个参数完全匹配(区分大小写),示例导航代码:
    await Shell.Current.GoToAsync($"{nameof(MyPage)}?Id=123");
    
  • 必须确保BaseViewModel正确实现INotifyPropertyChanged接口,且SetProperty方法能正确触发属性变更通知——这是查询参数能赋值到ViewModel的核心前提。
  • 不要在ViewModel构造函数中直接使用查询参数,因为查询参数是在页面导航完成后才会被赋值,需通过属性变更回调触发数据加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 19:52:38