winform是一老技术,感觉都有点掉牙了(我近20年前就是从winform开始接触.net的);blazor,是微软技术圈里的新宠,正在被悉心照顾。当这一老一少的技术碰撞后,会有什么火花?
.net v6.0.0-preview.3,给winform和blazor结合带来了前提。https://github.com/axzxs2001/Asp.NetCoreExperiment/tree/master/Asp.NetCoreExperiment/Blazor/BlazorWinForm 是我写的一个简单的demo,在winform窗体中引入blazor。
先看一下长什么样:
是一个简单的用助记码查询药品的例子,输入框查询按钮,table的样式都是Bootstrap5.0的,外层是一个winform的Form窗体。
具体实现,先看项目文件csproj的不一样:Sdk要换成Microsoft.NET.Sdk.Razor,然后是要通过nuget引入这些包。
<Project Sdk="Microsoft.NET.Sdk.Razor"> <PropertyGroup> <OutputType>WinExe</OutputType> <TargetFramework>net6.0-windows</TargetFramework> <UseWindowsForms>true</UseWindowsForms> </PropertyGroup> <ItemGroup> <PackageReference Include="Dapper" Version="2.0.78" /> <PackageReference Include="Microsoft.AspNetCore.Components.WebView.WindowsForms" Version="6.0.0-preview.3.21201.13" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0-preview.3.21201.4" /> <PackageReference Include="Microsoft.NET.Sdk.Razor" Version="5.0.0-preview.8.20414.8" /> <PackageReference Include="System.Data.SqlClient" Version="4.8.2" /> </ItemGroup> <ItemGroup> <Content Update="wwwroot\app.css"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </Content> <Content Update="wwwroot\Query.razor"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </Content> <Content Update="wwwroot\css\bootstrap.min.css"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </Content> <Content Update="wwwroot\index.html"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </Content> <Content Update="wwwroot\js\bootstrap.min.js"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </Content> </ItemGroup> <ItemGroup> <None Update="wwwroot\app.css"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> <None Update="wwwroot\Query.razor"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </None> <None Update="wwwroot\index.html"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </None> </ItemGroup> </Project>
通过csproj也知道,我是添加了wwwroot文件夹,并添加了一些前端文件:
index.html是一个模板页,引入一些css和js
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <title>Blazor app</title> <base href="/" /> <link href="{PROJECT NAME}.styles.css" rel="stylesheet" /> <link href="app.css" rel="stylesheet" /> <link href="css/bootstrap.min.css" rel="stylesheet" /> </head> <body> <div id="app" class="container"></div> <div id="blazor-error-ui"> An unhandled error has occurred. <a href="" class="reload">Reload</a> <a class="dismiss">