Issue with WebView2 control inside WPF/Windows Form for a VSTO project

Viewed 413

I have created a C# Outlook VSTO project with a wpf User control which is embedded in a Windows Form.

The idea is to navigate to an specific website using the WebView2 control that was added to the wpf User control.

The issue is that the control isn't rendering any website. On the other hand when I use a WebView2 control in a different project just with the Windows Form or WPF it works.

The package I'm using "Microsoft.Web.WebView2"

This is my Windows Form code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FraudDetector.Controls
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            this.eHost.Child = new FDView();
        }
    }
}

This is my wpf xaml:

<UserControl
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:FraudDetector.Controls"
             xmlns:Wpf="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid Background="Red">
        <Wpf:WebView2 Source="https://www.google.com/"/>
    </Grid>
</UserControl>

Do some one have some idea?

1 Answers

I found a solution by setting the userdata folder ("cache") as follows:

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
    }

    private async void MainForm_Load(object sender, EventArgs e)
    {
        await InitializeCoreWebView2Async();
        //Navigate to URI by setting Source property
        webView.Source = new Uri("https://www.google.com/");
    }

    private async Task InitializeCoreWebView2Async()
    {
        string tempWebCacheDir = @"C:\Temp";
        //Specify options regarding the coreView2 initialization process
        var webView2Environment = await CoreWebView2Environment.CreateAsync(userDataFolder: tempWebCacheDir);
        //CoreWebView2 creation
        await webView.EnsureCoreWebView2Async(webView2Environment);
    }
}

Remember to add the using Microsoft.Web.WebView2.Core at the top of the class.

Related