Home > OS >  Set WebView2 data folder in WPF/MVVM/Caliburn setup
Set WebView2 data folder in WPF/MVVM/Caliburn setup

Time:06-22

We have WPF app which is using Caliburn/MVVM setup.
ViewModel registration in Bootstrapper:

builder.RegisterType<CustomWebViewModel>().As<Screen>();  

WebView2 creation in CustomWebView.xaml:

<Grid>
    <wv2:WebView2 x:Name="WebView2" Source="{Binding WebAddress, Mode=OneWay, 
        UpdateSourceTrigger=PropertyChanged, NotifyOnSourceUpdated=True}" />
</Grid>  

In developement environment app runs smoothly: WebView2 shows correct content.
However in production this app is installed in C:\Program Files\Company\Product\ folder.
When started it throws message:

Microsoft Edge can't read and write to its data directory: C:\Program Files\Company\Product\Product.exe.WebView2\EBWebView

The reason is that WebView2 needs to be configured to use data folder that app would have a permission to use.
This piece of code does it:

        var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
        var userDataFolder = System.IO.Path.Combine(appData, "CustomWebView2");

        var task = await CoreWebView2Environment.CreateAsync(null, userDataFolder);
        var webView2 = (WebView2)this.FindName("WebView2");
        if (webView2 != null)
            await webView2.EnsureCoreWebView2Async(task);

Question: where do I call this piece of code in this setup?
I tried OnCoreWebView2InitializationCompleted and OnContentLoading but in both cases EnsureCoreWebView2Async throws:

System.ArgumentException: 'WebView2 was already initialized with a different CoreWebView2Environment. Check to see if the Source property was already set or EnsureCoreWebView2Async was previously called with different values.'

CodePudding user response:

Call EnsureCoreWebView2Async before you set the Source of the WebView2 control.

So remove the binding from your XAML markup:

<wv2:WebView2 x:Name="WebView2" />

...and set it programmatically:

var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var userDataFolder = System.IO.Path.Combine(appData, "CustomWebView2");

var task = await CoreWebView2Environment.CreateAsync(null, userDataFolder);
var webView2 = (WebView2)this.FindName("WebView2");
if (webView2 != null)
{
    await webView2.EnsureCoreWebView2Async(task);
    webView2.SetBinding(WebView2.SourceProperty, new Binding("WebAddress"));
}
  • Related