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):