我是 WinUI 3 的新手,但我之前曾使用过 WinForms 应用程序。在 WinForms 中,WebView2 必须通过 NuGet 安装,但它包含在 WinUI 3 中。
我发现WinUi3中的WebView2在
window(MainWindow)
中工作正常,但是如果我将WebView2添加到如下页面:
<?xml version="1.0" encoding="utf-8"?>
<Page
<!--Some properties-->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5*"/>
<ColumnDefinition Width="5*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="9*"/>
</Grid.RowDefinitions>
<Border Grid.Row="0" Grid.ColumnSpan="2" Background="Blue"/>
<controls:WebView2 x:Name="Browser" Grid.Row="1" Grid.ColumnSpan="2" Source="https://www.google.com" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" DefaultBackgroundColor="Black"/>
</Grid>
</Page>
并使用
Frame
在主窗口中导航页面:
// Adding a Tab with Frame
muxc.TabViewItem NewTab = new();
Frame TabFrame = new();
NewTab.Content = TabFrame;
NewTab.Header = "New";
TabFrame.Navigate(typeof(TabPage));
TabControl.TabItems.Add(NewTab);
窗口将如下图所示:
。
显示蓝色矩形,表示页面加载正确。蓝色矩形下方的部分是WebView2,它甚至没有用
DefaultBackgroundColor
显示。
我使用
await Browser.EnsureCoreWebView2Async();
和 Console.WriteLine(Browser.Parent.ToString());
来查看我的 WebView2 实例是否存在。前一个片段只是继续等待,而后一个片段抛出一个 NullReferenceException
。我该如何解决这个问题?
您不需要
WebView2
的命名空间。
<!--
<controls:WebView2 Source="https://www.google.com" />
-->
<WebView2 Source="https://www.google.com" />