I am new to WinUI 3, but I worked on WinForms app before. In WinForms, WebView2 has to be installed via NuGet, but it is included in WinUI 3.
I found that WebView2 in WinUi3 works normally in window(MainWindow)
, but If I add WebView2 to a page like:
<?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>
And navigate the page in main window with 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);
The window will look like the following image:
.
It shows the blue rectangle, which means the page loaded correctly. The part under the blue rectangle is WebView2, which doesn't even show with the DefaultBackgroundColor
.
I used await Browser.EnsureCoreWebView2Async();
and Console.WriteLine(Browser.Parent.ToString());
to see if my WebView2 instance exists. The former snippet just keeps waiting and the latter throws a NullReferenceException
. How can I fix this?
You don't need a namespace for WebView2
.
<!--
<controls:WebView2 Source="https://www.google.com" />
-->
<WebView2 Source="https://www.google.com" />
UPDATE
I created a sample app and did reproduce your issue. You also need to set the TabView
's VerticalAlignment
to Stretch
.
The following is the code that works on my side:
MainPage.xaml
<TabView
VerticalAlignment="Stretch"
AddTabButtonClick="TabViewControl_AddTabButtonClick" />
MainPage.xaml.cs
private void TabViewControl_AddTabButtonClick(TabView sender, object args)
{
var tabViewContent = new Frame();
tabViewContent.Navigate(typeof(WebView2Page));
var tabViewItem = new TabViewItem()
{
Header = "New Tab",
Content = tabViewContent,
};
sender.TabItems.Add(tabViewItem);
sender.SelectedItem = tabViewItem;
}
WebView2Page.xaml
<Grid RowDefinitions="Auto,*">
<TextBlock
Grid.Row="0"
Text="WebView2" />
<WebView2
x:Name="WebView2Control"
Grid.Row="1"
Source="https://www.google.com" />
</Grid>