在.NET MAUI Blazor中添加原生XAML页面的方法咨询
在MAUI Blazor中添加XAML原生页面并混用Blazor组件
一、创建XAML原生页面
- 右键你的MAUI Blazor项目,选择「添加 -> 新建项」,在模板里选「MAUI Content Page (XAML)」,命名为
NativePage.xaml(可自定义名称) - 打开
NativePage.xaml,编写原生XAML布局,还能直接嵌入Blazor组件:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:YourAppName.Components" x:Class="YourAppName.NativePage" Title="原生页面"> <StackLayout Padding="20" Spacing="15"> <Label Text="这是纯XAML原生页面" FontSize="Large"/> <Button Text="返回Blazor页面" Clicked="OnBackButtonClicked"/> <!-- 嵌入Blazor组件 --> <BlazorWebView HostPage="wwwroot/index.html" HeightRequest="300"> <BlazorWebView.RootComponents> <RootComponent Selector="#app" ComponentType="{x:Type local:Counter}"/> </BlazorWebView.RootComponents> </BlazorWebView> </StackLayout> </ContentPage>
- 打开对应的
NativePage.xaml.cs,添加返回逻辑:
namespace YourAppName; public partial class NativePage : ContentPage { public NativePage() { InitializeComponent(); } private void OnBackButtonClicked(object sender, EventArgs e) { Navigation.PopAsync(); } }
二、从Blazor页面跳转到原生页面
- 在任意Blazor组件(比如
Index.razor)中添加跳转按钮,通过MAUI导航服务实现:
<button @onclick="NavigateToNativePage" class="btn btn-success">打开原生XAML页面</button> @code { private void NavigateToNativePage() { var mainPage = Microsoft.Maui.Controls.Application.Current.MainPage as NavigationPage; mainPage?.PushAsync(new NativePage()); } }
三、注意事项
- 确保你的MAUI主页面是
NavigationPage,否则无法正常进行页面栈跳转,可在App.xaml.cs中配置:
public App() { InitializeComponent(); MainPage = new NavigationPage(new MainPage()); }
BlazorWebView的HostPage必须指向项目wwwroot目录下的index.html,这是Blazor的宿主页面- 嵌入Blazor组件时,要在XAML中声明组件所在的命名空间(比如示例中的
xmlns:local="clr-namespace:YourAppName.Components")
内容的提问来源于stack exchange,提问作者Igal Flegmann
相关产品推荐
相关产品推荐

