.NET Maui Blazor Hybrid:打开第二个窗口时如何传递参数
.NET MAUI Blazor Hybrid 新窗口传递参数的可行方案
你直接给HomePage实例的test属性赋值的方式不可行。因为[Parameter]是Blazor组件接收父组件传参的专属标记,而HomePage是承载Blazor内容的MAUI页面,直接实例化赋值不会被Blazor框架识别为组件参数。
以下是几种可行的实现方法:
方法一:通过MAUI页面自定义属性传递
- 给承载Blazor的MAUI页面(比如
HomePage)添加自定义属性:
public class HomePage : MauiBlazorWebViewPage { public string TestParam { get; set; } }
- 打开新窗口时给该属性赋值:
private void OnOpenWindowClicked() { var secondWindow = new Window { Page = new HomePage { TestParam = "test" } }; Application.Current.OpenWindow(secondWindow); }
- 在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组件是通过路由访问的,可以用查询参数传递:
- 打开新窗口后导航到带参数的路由:
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"); }
- 在Blazor组件中通过
[SupplyParameterFromQuery]接收参数:
@page "/home" @code { [Parameter] [SupplyParameterFromQuery(Name = "test")] public string test { get; set; } = ""; }
方法三:使用全局状态服务传递
适合需要在多个组件/窗口间共享参数的场景:
- 创建全局参数服务:
public class ParamService { public string CurrentTestParam { get; set; } }
- 在
MauiProgram.cs中注册为单例:
builder.Services.AddSingleton<ParamService>();
- 打开窗口前设置参数:
private void OnOpenWindowClicked() { var paramService = Application.Current.Services.GetRequiredService<ParamService>(); paramService.CurrentTestParam = "test"; var newWindow = new Window(new HomePage()); Application.Current.OpenWindow(newWindow); }
- 在Blazor组件中注入服务获取参数:
@inject ParamService ParamService @code { private string test; protected override void OnInitialized() { test = ParamService.CurrentTestParam ?? string.Empty; // 可选:获取后清空参数,避免后续窗口复用 // ParamService.CurrentTestParam = null; } }
内容的提问来源于stack exchange,提问作者Jeremy
相关产品推荐
相关产品推荐

