7

I'm trying to use WebView2 in a WPF application. I read in the docs and in other posts as well, that I should call the EnsureCoreWebView2Async() or set the Source property in order to initialize the WebView. If I set the Source, it loads the web page correctly, but I can't do this way, because I have the html content in memory (and it's not allowed to write to disk).

So I tried to call the initialization method:

var webView = new WebView2();

webView.NavigationCompleted += Navigation_Completed;
webView.Initialized += new EventHandler((object sender, EventArgs e) => { 
    webView.NavigateToString(myHtml);
});

await webView.EnsureCoreWebView2Async(null);

Running of this code is blocked by the EnsureCoreWebView2Async() method. I can even wait for one minute, but nothing happens, it's just stuck in initialization. No exception, no error message. I run this code on UI thread, but the same thing happened when I called this method on another thread.

Does anyone experienced this behavior? Any ideas?

Poul Bak
  • 10,450
  • 5
  • 32
  • 57
Attila Szász
  • 707
  • 4
  • 22

3 Answers3

4

To show the WebView2 manually, you must add it to the Controls collection of the form.

When you drop a WebView2 on the form, the designer does this automatically.

Simply call:

Controls.Add(webView)
await webView.EnsureCoreWebView2Async(null);

Now you should be able to display your html.

Update:

You can still drop the WebView2 on your form, if you prefer, just don't set the Source property.

Then you can use the designer to assign event handlers and in Initialized event you call:

webView.NavigateToString(myHtml);

just as you do now.

Poul Bak
  • 10,450
  • 5
  • 32
  • 57
1

If you need to go to a specific URI, I had to do the following calls.

As previously noted, do not set the Source attribute in your XAML.

Note that wv is the Name of my WevView2. Important part is that you still need to wait for the CoreWebView2 to be loaded. Now you can put any URI string in place of "https://www.microsoft.com"

    private async void wv_Initialized(object sender, EventArgs e)
    {
       await wv.EnsureCoreWebView2Async(null);
       wv.CoreWebView2.Navigate("https://www.microsoft.com");
    }
Manabu Tokunaga
  • 956
  • 10
  • 19
  • of course, you should call the `EnsureCoreWebView2Async` function. My problem was solved by adding the webView to the visual tree, by `Controls.Add(webView)` – Attila Szász Feb 05 '21 at 08:16
0

A proper place to initialize webview2 is on WPF OnContentRendered() Example:

   protected override async void OnContentRendered(EventArgs e)
   {
        base.OnContentRendered(e);

        var webView2Environment = await CoreWebView2Environment.CreateAsync();
        await webView2.EnsureCoreWebView2Async(webView2Environment);

   }
OKEEngine
  • 888
  • 11
  • 28