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

.NET 7 Maui中使用GoToAsync传Dictionary对象接收为Null问题

.NET 7 MAUI中GoToAsync传递对象为Null的解决方法

问题根源

代码存在两处关键不匹配,导致对象无法正确传递:

  1. QueryProperty与ObservableProperty名称不匹配:ViewModel中[QueryProperty(nameof(Salons), "Salons")]指定的目标属性Salons不存在,实际定义的ObservableProperty是单数的Salon。
  2. 构造函数执行时机限制:QueryProperty的赋值在ViewModel构造函数执行后完成,因此构造函数内无法获取传递的对象。

修正步骤

1. 对齐ViewModel的QueryProperty配置

将QueryProperty的目标属性与ObservableProperty名称对应,确保传递的字典键与QueryProperty的第二个参数一致:

using xxx.Models;
using xxx.Views;
using Microsoft.Maui.Controls;
using System.Collections.ObjectModel;

namespace xxx.ViewModels;

// 第一个参数是ViewModel的属性名,第二个参数是传递时的字典键名
[QueryProperty(nameof(Salon), "Salons")]
public partial class TemplateSalonViewModel : BaseViewModel
{
    public TemplateSalonViewModel()
    {
        
    }

    [ObservableProperty]
    Salons salon;

    // 可选:对象赋值后需执行逻辑,重写自动生成的变更方法
    partial void OnSalonChanged(Salons oldValue, Salons newValue)
    {
        // 在此处理传递过来的newValue
    }
}

2. 确保目标页面绑定ViewModel

若未通过依赖注入自动设置BindingContext,需在目标页面构造函数中手动绑定:

namespace xxx.Views;

public partial class TemplateSalonPage : ContentPage
{
    public TemplateSalonPage(TemplateSalonViewModel viewModel)
    {
        InitializeComponent();
        BindingContext = viewModel;
    }
}

3. 验证字典传递的键名

你的GoToAsync代码中字典键"Salons"与修正后的QueryProperty参数一致,无需修改:

private async void ListView_ItemTapped(object sender, ItemTappedEventArgs e)
{
    var salons = e.Item as Salons;
    await Shell.Current.GoToAsync("TemplateSalonPage", true, new Dictionary<string, object>
    {
        {"Salons", salons }
    });
}

额外注意事项

  • 传递的Salons类需保证可序列化,复杂对象建议添加[Serializable]特性,且所有属性为公共可访问状态。
  • 不要在ViewModel构造函数中依赖Salon对象,相关逻辑应放在OnSalonChanged方法中执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 16:42:52