Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
saf-itpro opened this issue Jul 19, 2020 · 3 comments
Labels

Comments

@saf-itpro
Copy link

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

enter image description here

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

enter image description here

@jm-trd-ms jm-trd-ms added the cat: webview2 WebView-related content. label Aug 11, 2020
@cgeier
Copy link

cgeier commented Aug 15, 2020

I've tested the following code, which seems to work.

Create a new project named: WebView2WpfTest

VS 2017:

  • File
  • New
  • Project
  • Expand Installed
  • Expand Visual C#
  • WPF App (.NET Framework)
  • Name: WebView2WpfTest
  • Solution name: WebView2WpfTest
  • Framework: 4.6.2
  • Click OK

VS 2019:

  • File
  • New
  • Project
  • C# Windows Desktop
  • WPF App (.NET Framework)
  • Click Next
  • Project Name: WebView2WpfTest
  • Solution name: WebView2WpfTest
  • Framework: 4.6.2
  • Click Create

Open Solution Explorer

  • On menu, click View
  • Select Solution Explorer

Add WebView2 package

  • In Solution Explorer, right-click WebView2WpfTest project
  • Select Manage NuGet Packages...
  • Click Browse
  • Search: Microsoft.Web.WebView2
  • Check Include prerelease
  • Version: <select latest version that ends with "-prerelease"> (ex: 0.9.579-prerelease)
  • Click Install

Modify MainWindow.xaml code

  • In Solution Explorer, right-click MainWindow.xaml
  • Select View Designer
  • Replace the existing MainWindow.xaml code with the following:

MainWindow.xaml

<Window x:Class="WebView2WpfTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WebView2WpfTest"
        xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
        mc:Ignorable="d"
        Title="MainWindow" Height="550" Width="800" MinWidth="500">

    <DockPanel>
       
        <DockPanel DockPanel.Dock="Top">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="30"/>
                    <ColumnDefinition Width="300*"/>
                    <ColumnDefinition Width="10"/>
                    <ColumnDefinition Width="30"/>
                    <ColumnDefinition Width="10"/>
                    <ColumnDefinition Width="30"/>
                    <ColumnDefinition Width="10"/>
                </Grid.ColumnDefinitions>

                <Grid Grid.Column="0" Name="GridCol0">
                    <Label DockPanel.Dock="Left">URL:</Label>
                </Grid>
                
                <Grid Grid.Column="1" Name="GridCol1">
                    <TextBox Name = "addressBar"  HorizontalAlignment="Left" VerticalAlignment="Center" MinWidth="400" KeyDown="addressBar_KeyDown">https://www.microsoft.com</TextBox>
                </Grid>
                
                <Grid Grid.Column="2" Name="GridCol2"/>

                <Grid Grid.Column="3" Name="GridCol3">
                    <Button x:Name="ButtonGo" DockPanel.Dock="Right" Click="ButtonGo_Click" Content="Go" Width="30"/>
                </Grid>
                
                <Grid Grid.Column="4" Name="GridCol4"/>

                <Grid Grid.Column="5" Name="GridCol5">
                    <Button x:Name="ButtonPrint"  Click="ButtonPrint_Click" Content="Print" Width="30"/>
                </Grid>

                <Grid Grid.Column="6" Name="GridCol6"/>

            </Grid>
            
        </DockPanel>
        
        <wv2:WebView2 Name = "webView"
                  Source = "https://www.microsoft.com" 
        />
        
    </DockPanel>
</Window>


Modify MainWindow.xaml.cs code

  • In Solution Explorer, right-click MainWindow.xaml
  • Select View Code
  • Replace the existing MainWindow.xaml.cs code with the following:

MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Web.WebView2.Core;

namespace WebView2WpfTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            //subscribe to event (add event handler)
            webView.CoreWebView2Ready += WebView_CoreWebView2Ready;

            //InitializeWebView2Async();
        }

        private void WebView_CoreWebView2Ready(object sender, EventArgs e)
        {
            System.Diagnostics.Debug.Print("WebView_CoreWebView2Ready");
        }

        public async void InitializeWebView2Async()
        {
            //initialize CoreWebView2
            await webView.EnsureCoreWebView2Async();
        }

        private void ButtonGo_Click(object sender, RoutedEventArgs e)
        {
            if (webView != null && webView.CoreWebView2 != null)
            {
                webView.CoreWebView2.Navigate(addressBar.Text);
            }
        }

        private async void ButtonPrint_Click(object sender, RoutedEventArgs e)
        {
            if (webView != null && webView.CoreWebView2 != null)
            {
                await webView.CoreWebView2.ExecuteScriptAsync("window.print();");
            }
        }

        private void addressBar_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (webView != null && webView.CoreWebView2 != null)
                {
                    webView.CoreWebView2.Navigate(addressBar.Text);
                }
            }
        }
    }
}

Add AnotherWindow window

  • In Solution Explorer, right-click WebView2WpfTest project
  • Select Add
  • Select Window (WPF)...
  • Name: AnotherWindow.xaml

Modify AnotherWindow.xaml code

  • In Solution Explorer, right-click AnotherWindow.xaml
  • Select View Designer
  • Replace the existing AnotherWindow.xaml code with the following:

AnotherWindow.xaml

<Window x:Class="WebView2WpfTest.AnotherWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WebView2WpfTest"
        mc:Ignorable="d"
        Title="AnotherWindow" Height="450" Width="800" MinWidth="500">

    <DockPanel>
        <DockPanel>
            <Grid DockPanel.Dock="Top">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="10"/>
                    <ColumnDefinition Width="200*"/>
                    <ColumnDefinition Width="75"/>
                    <ColumnDefinition Width="10"/>
 
                </Grid.ColumnDefinitions>

                <Grid Grid.Column="0" Name="GridCol0" />

                <Grid Grid.Column="1" Name="GridCol1" />

                <Grid Grid.Column="2" Name="GridCol2">
                    <Button x:Name="ButtonPrint" Click="ButtonPrint_Click" Content="Print" Width="50" Height="30"/>
                </Grid>

                <Grid Grid.Column="3" Name="GridCol3" />
            </Grid>

            <Grid DockPanel.Dock="Bottom" />

        </DockPanel>
    </DockPanel>
</Window>


Modify AnotherWindow.xaml.cs code

  • In Solution Explorer, right-click AnotherWindow.xaml
  • Select View Code
  • Replace the existing AnotherWindow.xaml.cs code with the following:

AnotherWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WebView2WpfTest
{
    /// <summary>
    /// Interaction logic for AnotherWindow.xaml
    /// </summary>
    public partial class AnotherWindow : Window
    {
        bool isCoreWebView2Initialized = false;
        MainWindow mainWindow = null;
        bool navigationCompletedAdded = false;

        public AnotherWindow()
        {
            InitializeComponent();
        }

        private async void ButtonPrint_Click(object sender, RoutedEventArgs e)
        {
            if (mainWindow == null)
            {
                //create new instance
                mainWindow = new MainWindow();

                //subscribe to event (add event handler)
                mainWindow.Closing += MainWindow_Closing;
                mainWindow.Closed += MainWindow_Closed;

                //show window
                mainWindow.Show();
            }
            else
            {
                mainWindow.WindowState = WindowState.Normal;
                mainWindow.Show();
                mainWindow.Activate();
            }

            if (mainWindow.webView != null)
            {
                if (!isCoreWebView2Initialized)
                {
                    //initialize CoreWebView2
                    await mainWindow.webView.EnsureCoreWebView2Async();

                    //set value
                    isCoreWebView2Initialized = true;
                }

                if (!navigationCompletedAdded)
                {
                    //subscribe to event (add event handler)
                    mainWindow.webView.NavigationCompleted += WebView_NavigationCompleted;

                    //set value
                    navigationCompletedAdded = true;
                }
                else
                {
                    PrintContent();
                }
            }
            else
            {
                System.Diagnostics.Debug.Print("mainWindow.webview is null");
            }
        }

        private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //unsubscribe (remove event handler)
            mainWindow.webView.NavigationCompleted -= WebView_NavigationCompleted;

            //set value
            isCoreWebView2Initialized = false;
            navigationCompletedAdded = false;

            System.Diagnostics.Debug.Print("unsubscribed from mainWindow.webView.NavigationCompleted event");
        }

        private void MainWindow_Closed(object sender, EventArgs e)
        {
            //if mainWindow is closed, set value to null
            mainWindow = null;
        }

        private async void PrintContent()
        {
            await mainWindow.webView.CoreWebView2.ExecuteScriptAsync("window.print();");
        }
        private async void WebView_NavigationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationCompletedEventArgs e)
        {
            System.Diagnostics.Debug.Print("WebView_NavigationCompleted");
            PrintContent();
            
        }
    }
}

Modify App.xaml (change StartupUri from MainWindow.xaml to AnotherWindow.xaml)

  • In Solution Explorer, double-click App.xaml
  • Replace App.xaml code with the following:

App.xaml

<Application x:Class="WebView2WpfTest.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WebView2WpfTest"
             StartupUri="AnotherWindow.xaml">
    <Application.Resources>
         
    </Application.Resources>
</Application>

@Reezaali
Copy link
Contributor

@saf-itpro the engineering team responded on the linked issue. Please review. Thanks.

@Reezaali
Copy link
Contributor

I'll go ahead and close this issue now. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants