WebView2 Control: As shown below, the HTML String successfully loads via NavigateToString(...) call inside Button_Click(...)
event. But I need to have the HTML string loaded as soon as the Window
and/or its Grid
is loaded. But the following code either inside the constructor MainWindow(){...}
or inside rootGrid_Loadded(...)
event throws the error shown below:
Question: How can we have the issue resolved and have the HTML string
loaded right after either the Window
or the Grid
is loaded? Or are there better solutions/workarounds?
MainWindow.xaml:
<Window x:Class="WpfWebView2TEST.MainWindow"
.....
xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
mc:Ignorable="d"
Style="{StaticResource CustomWindowStyle}"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button x:Name="btnTest" Content=Test" Click="btnTest_Click"/>
<wv2:WebView2 Name="MyWebView" />
</Grid>
</Window>
NOTE: Call to MyLoadHTMLString() in the following constructor or the rootGrid_Loaded(...)
event throws the error shown below:
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
MyLoadHTMLString();
}
........
}
private void rootGrid_Loaded(object sender, RoutedEventArgs e)
{
MyLoadHTMLString();
}
public void MyLoadHTMLString()
{
string sHTML = "<!DOCTYPE html>" +
"<html lang="en" xmlns="http://www.w3.org/1999/xhtml">" +
"<head>" +
"<meta charset="utf-8" />" +
"<title>Test Title</title>" +
"</head>" +
"<body>" +
"<p>Test paragraph</p>" +
"</body>" +
"</html>";
MyWebView.NavigateToString(sHTML);
}
NOTE: Following Button click event successfully
loads the HTML string into WebView2
private void btnTest_Click(object sender, RoutedEventArgs e)
{
MyLoadHTMLString();
}
Error:
System.InvalidOperationException HResult=0x80131509 Message=Attempted to use WebView2 functionality which requires its CoreWebView2 prior to the CoreWebView2 being initialized. Call EnsureCoreWebView2Async or set the Source property first. Source=Microsoft.Web.WebView2.Wpf
UPDATE:
The second and third paragraph of this MSDN Doc seem to provide some resolution to such an issue. but I'm not sure how to implement it
See Question&Answers more detail:os