欢迎使用XX管理系统
        }
        else
        {
            @title
        }
        Blazor是微软出品的前端框架,对标谷歌的Flutter,用C#、css、html语言开发前端UI,组件化设计,支持嵌套组件与大多数前端框架react、vue等类似,不同的是开发语言不是JavaScript,但是它可以与JavaScript互操作。Host模式支持Blazor Server、Blazor WebAssembly和Blazor Hybrid(MAUI、WPF、WinForm),可用它来开发Web、移动App、桌面应用。
打开VS2022,创建新项目,选择Windows窗体应用,将工程文件sdk改成 Microsoft.NET.Sdk.Razor
添加 NuGet 包 Web 和 WebView.WindowsForms,创建后的工程文件如下:
  
    WinExe 
    net6.0-windows 
    enable 
    true 
    enable 
   
  
     
     
   
 
添加 wwwroot 文件夹,添加 index.html 和 css/app.css
    
    
    WinApp 
     
    
    
    
    Loading...
    
    
添加_Imports.razor
@using Microsoft.AspNetCore.Components.Web
添加App.razor,其中DynamicComponent是动态组件,动态显示Home和Setting等razor页面
    
         OnClickMenu(Menus[0])">
        
        
    
    
        @if (isHome)
        {
            欢迎使用XX管理系统
        }
        else
        {
            @title
        }
         
    
@code {
    private string? code = "Home";
    private string? title = "";
    private bool isHome = true;
    private Type? componentType;
    private MenuItem setting = new MenuItem("Setting", "系统设置", "fa fa-bars", typeof(Setting));
    private MenuItem[] Menus = new MenuItem[]
    {
        new MenuItem("Home", "首页", "fa fa-home", typeof(Home))
    };
    protected override void OnInitialized()
    {
        base.OnInitialized();
        componentType = Menus[0].Type;
    }
    private void OnClickMenu(MenuItem menu)
    {
        isHome = menu.Id == "Home";
        code = menu.Id;
        title = menu.Name;
        componentType = menu.Type;
    }
    private string Active(MenuItem menu) => code == menu.Id ? "active" : "";
    private record MenuItem(string Id, string Name, string Icon, Type Type);
}
在工具箱中拖动BlazorWebView控件到窗体Form1中
在Form1.cs构造函数中添加如下代码:
public Form1()
{
    InitializeComponent();
    var services = new ServiceCollection();
    services.AddBlazorWebView();
    blazorWebView.HostPage = "wwwroot\\index.html";
    blazorWebView.Services = services.BuildServiceProvider();
    blazorWebView.RootComponents.Add("#app");
}
 
添加Pages文件夹,添加 Pages/Home.razor文件
Home
Current count: @currentCount
@code {
    private int currentCount = 0;
    private void IncrementCount()
    {
        currentCount++;
    }
}