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

.NET Maui Blazor Hybrid:打开第二个窗口时如何传递参数

.NET MAUI Blazor Hybrid 新窗口传递参数的可行方案

你直接给HomePage实例的test属性赋值的方式不可行。因为[Parameter]是Blazor组件接收父组件传参的专属标记,而HomePage是承载Blazor内容的MAUI页面,直接实例化赋值不会被Blazor框架识别为组件参数。

以下是几种可行的实现方法:

方法一:通过MAUI页面自定义属性传递

  1. 给承载Blazor的MAUI页面(比如HomePage)添加自定义属性:
public class HomePage : MauiBlazorWebViewPage
{
    public string TestParam { get; set; }
}
  1. 打开新窗口时给该属性赋值:
private void OnOpenWindowClicked()
{
    var secondWindow = new Window
    {
        Page = new HomePage
        {
            TestParam = "test"
        }
    };
    Application.Current.OpenWindow(secondWindow);
}
  1. 在Blazor组件中通过MAUI上下文获取参数:
@inject NavigationManager NavManager
@code {
    private string test;

    protected override void OnInitialized()
    {
        if (NavManager is MauiNavigationManager mauiNavManager)
        {
            var currentPage = mauiNavManager.BlazorWebViewHandler?.MauiContext?.Page as HomePage;
            test = currentPage?.TestParam ?? string.Empty;
        }
    }
}

方法二:通过路由/查询参数传递

如果你的Blazor组件是通过路由访问的,可以用查询参数传递:

  1. 打开新窗口后导航到带参数的路由:
private async void OnOpenWindowClicked()
{
    var blazorHostPage = new MainPage(); // 你的MAUI Blazor宿主页面
    var newWindow = new Window(blazorHostPage);
    Application.Current.OpenWindow(newWindow);

    // 等待窗口初始化完成后导航
    await Task.Delay(100);
    blazorHostPage.BlazorWebView.NavigateTo("/home?test=test");
}
  1. 在Blazor组件中通过[SupplyParameterFromQuery]接收参数:
@page "/home"
@code {
    [Parameter]
    [SupplyParameterFromQuery(Name = "test")]
    public string test { get; set; } = "";
}

方法三:使用全局状态服务传递

适合需要在多个组件/窗口间共享参数的场景:

  1. 创建全局参数服务:
public class ParamService
{
    public string CurrentTestParam { get; set; }
}
  1. 在MauiProgram.cs中注册为单例:
builder.Services.AddSingleton<ParamService>();
  1. 打开窗口前设置参数:
private void OnOpenWindowClicked()
{
    var paramService = Application.Current.Services.GetRequiredService<ParamService>();
    paramService.CurrentTestParam = "test";

    var newWindow = new Window(new HomePage());
    Application.Current.OpenWindow(newWindow);
}
  1. 在Blazor组件中注入服务获取参数:
@inject ParamService ParamService
@code {
    private string test;

    protected override void OnInitialized()
    {
        test = ParamService.CurrentTestParam ?? string.Empty;
        // 可选:获取后清空参数,避免后续窗口复用
        // ParamService.CurrentTestParam = null;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 11:42:47