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

.NET MAUI中如何通过ShowPopupAsync在ViewModel间传递数据?

在MAUI Community Toolkit Popup中向ViewModel传递数据

核心结论

不需要使用ApplyQueryAttributes,因为Popup不属于MAUI导航栈的页面体系,无法通过NavigateToAsync的查询参数方式传参,以下是两种实用的实现方式:


方法1:实例化Popup ViewModel时直接传参

这是最直观的方式,打开Popup前先创建其ViewModel并传入数据,再绑定到Popup的BindingContext。

调用方ViewModel代码:

private async Task OpenTargetPopup()
{
    // 准备要传递的字符串、整数数据
    string targetUserName = "Alice";
    int targetUserId = 456;

    // 直接通过构造函数传入参数实例化Popup的ViewModel
    var popupViewModel = new TargetPopupViewModel(targetUserName, targetUserId);
    
    // 创建Popup页面并绑定ViewModel
    var popup = new TargetPopupPage
    {
        BindingContext = popupViewModel
    };

    // 打开Popup
    await PopupExtensions.ShowPopupAsync(this, popup);
}

Popup的ViewModel代码:

public class TargetPopupViewModel
{
    // 接收并存储传递来的数据
    public string UserName { get; }
    public int UserId { get; }

    // 通过构造函数接收参数
    public TargetPopupViewModel(string userName, int userId)
    {
        UserName = userName;
        UserId = userId;
    }
}

方法2:通过Popup页面的绑定属性传递数据

如果Popup页面已经预设了ViewModel,可以先给Popup设置属性,再在页面初始化时同步给ViewModel。

Popup页面代码:

public partial class TargetPopupPage : Popup
{
    // 定义绑定属性用于接收外部传入的整数
    public static readonly BindableProperty UserIdProperty =
        BindableProperty.Create(nameof(UserId), typeof(int), typeof(TargetPopupPage), default(int));

    public int UserId
    {
        get => (int)GetValue(UserIdProperty);
        set => SetValue(UserIdProperty, value);
    }

    // 定义绑定属性用于接收外部传入的字符串
    public static readonly BindableProperty UserNameProperty =
        BindableProperty.Create(nameof(UserName), typeof(string), typeof(TargetPopupPage), string.Empty);

    public string UserName
    {
        get => (string)GetValue(UserNameProperty);
        set => SetValue(UserNameProperty, value);
    }

    public TargetPopupPage()
    {
        InitializeComponent();
        
        // 页面初始化时将属性值传递给ViewModel
        if (BindingContext is TargetPopupViewModel vm)
        {
            vm.UserId = UserId;
            vm.UserName = UserName;
        }
    }
}

调用方打开Popup的代码:

private async Task OpenTargetPopup()
{
    var popup = new TargetPopupPage
    {
        UserId = 456,
        UserName = "Alice"
    };

    await PopupExtensions.ShowPopupAsync(this, popup);
}

关于ApplyQueryAttributes的补充

ApplyQueryAttributes仅适用于MAUI导航栈中的ContentPage类页面,通过NavigateToAsync传递查询参数时使用。Popup是独立的弹窗组件,不依赖导航栈,因此这套机制对Popup无效,不要尝试用这种方式传参。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 13:38:30