i want to use blazorapp1 web application to mauiapp1 for both mobile and windows application
Integrating a Blazor web application into a .NET MAUI (Multi-platform App UI) application allows you to reuse your Blazor components across different platforms, including mobile (iOS and Android) and desktop (Windows and macOS). Here's a step-by-step guide to achieve this:
Create a .NET MAUI App:
MauiApp1
.Add Blazor Support to Your MAUI App:
MauiApp1.csproj
file.<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.WebView.Maui" Version="6.0.0" />
</ItemGroup>
Create a Blazor Component:
MauiApp1
project, add a new folder named Components
.MyComponent.razor
) to the Components
folder.MyComponent.razor
:
<h3>Hello from Blazor!</h3>
Configure the MAUI App to Use Blazor:
MauiProgram.cs
file.CreateMauiApp
method to register Blazor services:
using Microsoft.AspNetCore.Components.WebView.Maui;
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
});
builder.Services.AddMauiBlazorWebView();
return builder.Build();
}
}
Update the MainPage to Use BlazorWebView:
MainPage.xaml
file.BlazorWebView
:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MauiApp1"
xmlns:blazor="clr-namespace:Microsoft.AspNetCore.Components.WebView.Maui;assembly=Microsoft.AspNetCore.Components.WebView.Maui"
x:Class="MauiApp1.MainPage">
<blazor:BlazorWebView HostPage="wwwroot/index.html">
<blazor:BlazorWebView.RootComponents>
<blazor:RootComponent Selector="#app" ComponentType="{x:Type local:Main}" />
</blazor:BlazorWebView.RootComponents>
</blazor:BlazorWebView>
</ContentPage>
Create the Blazor Host Page:
MauiApp1
project, create a new folder named wwwroot
.index.html
to the wwwroot
folder.index.html
:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Blazor in MAUI</title>
</head>
<body>
<div id="app">Loading...</div>
<script src="_framework/blazor.webassembly.js"></script>
</body>
</html>
Run the Application:
By following these steps, you have successfully integrated a Blazor component into a .NET MAUI application. This allows you to leverage your Blazor components across multiple platforms, providing a consistent user experience on mobile and desktop applications.