WinUI 3.0 is Microsoft’s upcoming UI framework to build modern, native Windows applications.

WinUI is developed open source on https://github.com/microsoft/microsoft-ui-xaml

Last week WinUI 3.0 alpha 2 came out, and Microsoft introduced a WebView2 control that is based on Microsoft Edge Chromium. That means you can run all the modern, awesome web stuff in that WebView2 control if you want.

The Goal

I thought I give WebView2 a try, and hey, why not trying to host a web app in WebView2 that is built with my favorite Single Page Application (SPA) framework: Blazor!

But just hosting would be easy. I want to call a method in the Blazor App from my WinUI app.

What I created

What I ended up is the simple WinUI 3 app that you see below.

At the top of the WinUI application is a WinUI TextBox where you can enter a firstName (it contains “Thomas” above), and a WinUI Button with the Text “Update Blazor from WinUI”.

The Blazor application is shown at the bottom of the application window in a WebView2 control. The Blazor app contains a simple component with an input field that contains the text Julia.

When you click on the WinUI Button “Update Blazor from WinUI” , the text in that Blazor component’s input field is updated with the text from the WinUI TextBox. Voila:

To implement this WinUI to Blazor communication, you could of course use some kind of server communication via SignalR. With SignalR, the WinUI app would call the server, and the server would call into the Blazor app. But instead of using SingalR, I wanted to call into the Blazor app directly, as it is already in the WinUI app.

I managed to call from WinUI into Blazor via Blazor’s JavaScript Interop. The WebView2 has an ExecuteScriptAsync method that allows you to execute JavaScript code in the hosted web app.

Show Me the Code

All the code of this post is available on GitHub: https://github.com/thomasclaudiushuber/WinUI3-WebView2-Hosting-BlazorApp

Let’s look at the most important parts, and let’s start with the Blazor app.

#.net #blazor #javascript #winui #programming #csharp

Hosting a Blazor App in WinUI 3 with WebView2
11.50 GEEK