In my wpf application i try to show a webView2 for a login, even though when i navigate to the view and start the initialization nothing happens. I've tried many options and solutions i found in the internet and that worked for others but nothing helped.
The Code:
private WebView2 m_webView21;
public WebView2 WebView21 { get => m_webView21; set => SetProperty(ref m_webView21, value); }
protected async Task<WebView2> CreateBrowserAndLoadUrlAsync(string url)
{
webView21 = new WebView2();
webView21.CoreWebView2InitializationCompleted += WebView21_CoreWebView2InitializationCompleted;
Debug.WriteLine("InitializeAsync");
await webView21.EnsureCoreWebView2Async();
Debug.WriteLine("WebView2 Runtime version: " + webView21.CoreWebView2.Environment.BrowserVersionString);
SetBrowserHostVisibility(Visibility.Visible);
if (webView21 != null && webView21.CoreWebView2 != null)
{
webView21.CoreWebView2.Navigate(url);
}
return webView21;
}
private void WebView21_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
{
webView21.Loaded += Browser_FrameLoadEnd;
webView21.Initialized += Browser_InitializedChanged;
}
--Xaml Code--
<Grid Background="Transparent">
<wv2:WebView2 Visibility="Visible" Source="{Binding WebView21.Source.AbsoluteUri, Mode=OneWay}"/>
</Grid>
This is the first thing i'm calling in my viewmodel from the OnNavigatedTo(). Everything works as it should untig it comes to the EnsureCoreWebViewAsync() - from this function it never returns - just nothing happens.
When i do not initialize the webview2 and just set the source to the uri everything works fine aswell. But no events or anything get fired (e.g. NavigationCompleted, SourceChanged, etc.) and i need those events ofc.
I installed the correct runtime i also installed the WebView2 Plugin of course. Also tried different enviroments nothing helped.
So the actual question is, is it even possible to initialize the WebView2 from the Viewmodel?
I found the solution. I had to use a placeholder in my xaml which later init's the webView2 in my Viewmodel.
Just change the xaml code from the question with this and it should work fine
<ContentControl Content="{Binding WebView21, Mode=OneWay}" />
Thanks for all the helpful comments :))