Reputation: 23749
WPF WebView2 Control is inside the MainWindow.xaml
(shown below). When calling ExecuteScriptAsync(...) from a Button click event inside MainWindow.xaml.cs
(code shown below), it works fine. But when accessing WebView2
control from another class AnotherWindow.xaml.cs
(in the same project) and call the same ExecuteScriptAsync(...)
method it complains about CoreWebView2
being null
Question: What I may be missing, and how can it be resolved?
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="webView" />
</Grid>
</Window>
Remark 1: Following works fine when button and its click event is inside MainWindow.xaml.cs
private async void btnTest1_Click(object sender, RoutedEventArgs e)
{
await webView.CoreWebView2.ExecuteScriptAsync("window.print();");
}
The debug mode shows below that CoreWebView2
is not null (and hence the code works):
Remark 2: Following does NOT work when button and its click event is inside another window AnotherWindow.xaml.cs
in the same project but accessing the WebView2
control of the MainWindow.xaml
private async void btnPrint_Click(object sender, RoutedEventArgs e)
{
MainWindow mainWindow = new MainWindow();
await mainWindow.webView.CoreWebView2.ExecuteScriptAsync("window.print();");
}
The debug mode inside the AnotherWindow.xaml.cs
shows below that CoreWebView2
is not null (and hence throws the error: Object reference not set):
Upvotes: 0
Views: 4688
Reputation: 4377
You need to initialize the CoreWebView2 as described in the WebView2 docs:
Upon creation, the control's CoreWebView2 property will be null. This is because creating the CoreWebView2 is an expensive operation which involves things like launching Edge browser processes. There are two ways to cause the CoreWebView2 to be created: 1) Call the EnsureCoreWebView2Async method. This is referred to as explicit initialization. 2) Set the Source property (which could be done from markup, for example).
From your second question, you cannot use the Source property to provide the HTML of the document. You need to call EnsureCoreWebView2Async, wait for it to complete, and then call NavigateToString on the CoreWebView2:
await webView.EnsureCoreWebView2Async(null);
webView.CoreWebView2.NavigateToString(htmlString);
Upvotes: 2