Search code examples
c#windowsuwp

How to show WebView2 content without flicker?


In my UWP project, a page contains several subpages. One subpage has a WebView2(from Microsoft.UI.Xaml.Controls). And I need to use it to open some link, e.g. www.bing.com, only once. When navigate to the web page done, I need to switch to other subpage and back then.

I find that the WebView2's content will flicker: from black to the web content. The flicker issue is caused by WebView2's visibility change.

Below is my code, any advise?

UI:

<Page
    x:Class="WebView2FlickerDemo.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:WebView2FlickerDemo"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    xmlns:controls="using:Microsoft.UI.Xaml.Controls"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <Button Click="Button_Click" Width="200" Height="100"></Button>

        <controls:WebView2 x:Name="WebView2" Height="567.55" Width="792" Margin="200 150 0 0" Visibility="Visible"/>
        <Grid x:Name="myGrid" Background="Blue" Height="567.55" Width="792" Margin="200 150 0 0" Visibility="Collapsed"></Grid>
    </Grid>
</Page>

C#:

public MainPage()
{
    this.InitializeComponent();
    StartWebView2();
}

private async void StartWebView2()
{
    try
    {
        await WebView2.EnsureCoreWebView2Async();
        WebView2.CoreWebView2.Navigate("https:///www.bing.com");
    }
    catch (Exception ex)
    {
    }
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    if (WebView2.Visibility == Visibility.Visible)
    {
        WebView2.Visibility = Visibility.Collapsed;
        myGrid.Visibility = Visibility.Visible;
    }
    else if (WebView2.Visibility == Visibility.Collapsed)
    {
        WebView2.Visibility = Visibility.Visible;
        myGrid.Visibility = Visibility.Collapsed;
    }
}

Solution

  • I can reproduce the same behavior. Since I don't know your specific scenario, based on the code provided so far, if you don't want the current flickering behavior, it is recommended to delete the WebView2.Visibility part and use myGrid to cover the webview2.

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (myGrid.Visibility == Visibility.Visible)
            {
                // WebView2.Visibility = Visibility.Collapsed;
    
                //WebView2.Opacity = 1;
                myGrid.Visibility = Visibility.Collapsed;
            }
            else if (myGrid.Visibility == Visibility.Collapsed)
            {
                //WebView2.Visibility = Visibility.Visible;
    
                //WebView2.Opacity = 0;
                myGrid.Visibility = Visibility.Visible;
            }
        }