Sunday, May 9, 2021

Using WebView2 inside WinUI 3 in Desktop project (Part I)

Microsoft Edge WebView2 control allows you to use Chromium Engine in any type of apps (including WinForms, WPF, WinUI 3). In several articles we will describe how to use WebView2 control inside WinUI 3 in Desktop project which is the part of Microsoft Reunion.

To create this type of this project first you need to install Microsoft Reunion Extension:

Now we can create our WinUI 3 in Desktop project:

After creating the project make sure Application->Target Framework is set and also in case of Reunion version 0.5.6 you may need to add the following lines:

Now let's add WebView2 to MainWindow content.

Now we can navigate to whatever page we need in code using Source property and also we can add NavigationStarting and NavigationCompleted events.


using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.Web.WebView2.Core;
using System;

public MainWindow()
{
    this.InitializeComponent();

	webView.Source = new Uri("https://microsoft.com");

	webView.NavigationStarting += WebView_NavigationStarting;
	webView.NavigationCompleted += WebView_NavigationCompleted;
}

First, NavigationStarting will be triggered:

private void WebView_NavigationStarting(WebView2 sender, CoreWebView2NavigationStartingEventArgs args)
{
            
}

And then, NavigationCompleted will be triggered:

private void WebView_NavigationCompleted(WebView2 sender, CoreWebView2NavigationCompletedEventArgs args)
{
	bool success = args.IsSuccess;
}

By now our sample is very simple:

In Part 2 we will describe how to stop navigation, reload the page, go back, go forward and also inspect the page.

No comments:

Post a Comment