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

.NET MAUI中CollectionView选中值无法传递至详情页问题

.NET MAUI Shell导航传递Id失败问题排查与解决

你的问题核心原因是Shell的QueryProperty赋值时机晚于页面构造函数执行时机:当你在DetailPage的构造函数中设置lblText.Text = id.ToString()时,QueryProperty还没完成参数传递,此时id还是int类型的默认值0,所以Label始终显示0。

解决方案

有两种常用的修复方式,任选其一即可:

方式1:通过属性Setter实时更新UI

修改DetailPage的属性定义,在setter方法中更新Label文本,确保参数传递后立即刷新UI:

namespace b_records;

[QueryProperty(nameof(Id), "id")]
public partial class DetailPage : ContentPage
{
    private int _id;
    public int Id
    {
        get => _id;
        set
        {
            _id = value;
            // 参数赋值完成后直接更新Label
            lblText.Text = _id.ToString();
        }
    }

    public DetailPage()
    {
        InitializeComponent();
    }
}

方式2:在OnAppearing方法中更新UI

重写页面的OnAppearing方法,此时QueryProperty已经完成参数传递,再更新Label:

namespace b_records;

[QueryProperty(nameof(Id), "id")]
public partial class DetailPage : ContentPage
{
    public int Id { get; set; }

    public DetailPage()
    {
        InitializeComponent();
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();
        // 此时Id已经被QueryProperty赋值
        lblText.Text = Id.ToString();
    }
}

额外验证点

可以在MainPage的OnCollectionViewSelectionChanged方法中加个断点,确认(e.CurrentSelection.FirstOrDefault() as Record)不为null,且Id值是正确的,排除数据源本身的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 12:00:59