从同一项目中的另一个 XAML Window 访问时,CoreWebView2 为 null

CoreWebView2 is null when accessing it from another XAML Window in the same project

WPF WebView2 Control is inside the MainWindow.xaml (shown below). When calling ExecuteScriptAsync(...) 来自 MainWindow.xaml.cs 内的按钮单击事件(代码如下所示),它工作正常。但是当从另一个 class AnotherWindow.xaml.cs(在同一个项目中)访问 WebView2 控件并调用相同的 ExecuteScriptAsync(...) 方法时,它抱怨 CoreWebView2 为 null

问题:我可能遗漏了什么,如何解决?

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>

备注 1:当按钮及其点击事件在 MainWindow.xaml.cs

内时,以下工作正常
private async void btnTest1_Click(object sender, RoutedEventArgs e)
{
    await webView.CoreWebView2.ExecuteScriptAsync("window.print();");
}

下面的调试模式显示 CoreWebView2 不为空(因此代码有效):

备注 2:当按钮及其单击事件位于同一项目中的另一个 window AnotherWindow.xaml.cs 中但访问 WebView2控制MainWindow.xaml

private async void btnPrint_Click(object sender, RoutedEventArgs e)
{
    MainWindow mainWindow = new MainWindow();
    await mainWindow.webView.CoreWebView2.ExecuteScriptAsync("window.print();");
}

AnotherWindow.xaml.cs 中的调试模式在下面显示 CoreWebView2 不为空(因此抛出错误:未设置对象引用):

您需要按照the WebView2 docs中所述初始化 CoreWebView2:

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

从你的第二个问题来看,你不能使用 Source 属性 来提供文档的 HTML。您需要调用 EnsureCoreWebView2Async,等待它完成,然后在 CoreWebView2 上调用 NavigateToString:

   await webView.EnsureCoreWebView2Async(null);
   webView.CoreWebView2.NavigateToString(htmlString);