WinForm混合Blazor(上)

在之前,我发表过一篇文章,简单介绍WinForm通过WebView2加载Blazor,如下:

鸡肋还是革新——Blazor进WinForm

 今天接着这个话题,再深入一些。.

从C#中调用js函数

项目文件.csproj

<Project Sdk="Microsoft.NET.Sdk.Razor">
  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net7.0-windows</TargetFramework>
    <Nullable>enable</Nullable>
    <UseWindowsForms>true</UseWindowsForms>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="microsoft.aspnetcore.components.webview.windowsforms" Version="6.0.300-rc.1.5355" />
    <PackageReference Include="Microsoft.JSInterop" Version="7.0.0-preview.3.22178.4" />
  </ItemGroup>
  <ItemGroup>
    <Content Update="DomePage.razor">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
    </Content>
  </ItemGroup>
</Project>

添加wwwroot和index.html(其他引用文件,参见前一篇文章)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>WinFormsBlazor</title>
    <base href="/" />
    <link href="{PROJECT NAME}.styles.css" rel="stylesheet" />
    <link href="css/app.css" rel="stylesheet" />
    <link href="WinFormsBlazor.styles.css" rel="stylesheet" />
    <link href="css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
    <div id="app" class="container">Loading...</div>
    <div id="blazor-error-ui">
        An unhandled error has occurred.
        <a href="" class="reload">Reload</a>
        <a class="dismiss">