前言
开发技术
.NET 6 + MAUI + Blazor WebAssembly + Ant Desgin of Blazor(v3.4.0)
知识预览
什么是MAUI
MAUI 是.NET的一个多平台应用UI框架,用于使用C#和XAML创建本机移动和桌面。使用MAUI,可从单个共享代码库开发在Android、iOS、macOS和Windows上运行的应用。.MAUI是开源的,是Xamarin.Forms的演变,从移动方案扩展到桌面方案,UI控件从头开始重新生成,以确保性能和扩展性。
什么是WebAssembly
WebAssembly 是一种新的编码方式,可以在现代的网络浏览器中运行。它是一种低级的类汇编语言,具有紧凑的二进制格式,可以接近原生的性能运行,并为诸如C/C++,C# 和Rust等语言提供一个编译目标,以便它们可以在Web上运行。它也被设计为可以与JavaScript一起工作。
什么是Blazor
Blazor 是一个基于.NET和Razor构建的UI框架。Blazor应用程序可以作为ASP.NET应用程序的一部分在服务器上运行,也可以部署在用户计算机上的浏览器中运行,类似于单页应用程序(SPA).

开发详细
一、创建项目
首先,通过VS创建一个 .NET MAUI Blazor 应用,取名 “MauiBlazorDemo”。如果未找到此模板,则需要先安装工作负载 “ .NET Multi-platform App UI 开发 ”。

在Windows机器上启动调试,界面运行如下:

因为在项目中要使用 Ant Design of Blazor 框架,所以等把模板自带的一些文件删除。做法如下:

接着,我们再创建一个 Ant Design Pro Blazor 模板应用,叫 “MyAntDesignApp” (名字任意) ,所有选项默认即可。如果你未找到此模板,可通过命令 dotnet new install AntDesign.Templates 来安装。

创建之后,将 MyAntDesignApp 项目的以下文件拷贝到 MauiBlazorDemo 项目中。

为了能够读取 appsetings.json 的配置信息,我们将它从 wwwroot 目录移至根目录,并将文件属性的 “生成操作” 改为 MauiAsset。最终 MauiBlazorDemo 项目的文件结构如下:

程序启动执行顺序:

接下来,我们需要对 MauiBlazorDemo 项目的文件内容进行修改,确保功能可以正常运行。
二、修改项目
1. 为 MauiBlazorDemo 项目添加第三方Nuget包:
<ItemGroup><PackageReference Include="AntDesign.Charts" Version="0.3.1" /><PackageReference Include="AntDesign.ProLayout" Version="0.14.4" /><PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="6.0.0" /></ItemGroup>
public static class MauiProgram{public static MauiApp CreateMauiApp(){var builder = MauiApp.CreateBuilder();builder.UseMauiApp<App>().ConfigureFonts(fonts =>{fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");});var stream = FileSystem.OpenAppPackageFileAsync("appsettings.json").Result;builder.Configuration.AddJsonStream(stream);builder.Services.Configure<ProSettings>(builder.Configuration.GetSection("ProSettings"));builder.Services.AddMauiBlazorWebView();builder.Services.AddAntDesign();#if DEBUGbuilder.Services.AddBlazorWebViewDeveloperTools();#endifreturn builder.Build();}}
@using MainLayout = MauiBlazorDemo.Layouts.BasicLayout;<Router AppAssembly="@typeof(Main).Assembly"><Found Context="routeData"><RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" /><FocusOnNavigate RouteData="@routeData" Selector="h1" /></Found><NotFound><LayoutView Layout="@typeof(MainLayout)"><p role="alert">Sorry, there's nothing at this address.</p></LayoutView></NotFound></Router><AntContainer /> @*添加AntContainer组件*@
注:此文件等同 MyAntDesignApp 中的 App.razor 文件,名字不同而已。
4. 修改 _Imports.razor 代码如下:
@using System.Net.Http@using Microsoft.AspNetCore.Components.Forms@using Microsoft.AspNetCore.Components.Routing@using Microsoft.AspNetCore.Components.Web@using Microsoft.AspNetCore.Components.Web.Virtualization@using Microsoft.JSInterop@using MauiBlazorDemo@using MauiBlazorDemo.Layouts@using AntDesign@using AntDesign.Charts@using AntDesign.ProLayout
5. 最后对 Index.html 文件进行修改,将 <link /> 和 <script /> 语句替换如下:

三、运行项目
至此,Maui通过 WebView 嵌入AntBlazor的功能已基本告成 。文字稍作修改后,界面运行效果如下:
