Search code examples
c++uwp-xamlc++-winrt

Errors in creating a Webview2 sample app in UWP


I am following the steps mentioned here and am able to successfully create the sample app sans webview till Step 5. From Step6 onwards, things go wrong.

This is the current content of my MainPage.xaml:

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

    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
        <Button x:Name="myButton" Click="ClickHandler">Click Me</Button>
    </StackPanel>
</Page>

I added this block

xmlns:controls="using:Microsoft.UI.Xaml.Controls"

as well as

<controls:WebView2 x:Name="WebView2" Source="https://bing.com"/>

inside the StackPanel, with the XAML now looking like

    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
        <!--<Button x:Name="myButton" Click="ClickHandler">Click Me</Button>-->
        <controls:WebView2 x:Name="WebView2" Source="https://bing.com"/>
    </StackPanel>

This is what I see in the design editor

enter image description here

and upon building I encounter a lot of errors like

error C3083: 'Microsoft': the symbol to the left of a '::' must be a type (compiling source file MainPage.cpp)
error C3083: 'UI': the symbol to the left of a '::' must be a type (compiling source file MainPage.cpp)
error C3083: 'Xaml': the symbol to the left of a '::' must be a type (compiling source file MainPage.cpp)
error C3083: 'Controls': the symbol to the left of a '::' must be a type (compiling source file MainPage.cpp)
error C3646: 'WebView2': unknown override specifier (compiling source file MainPage.cpp)

essentially complaining about the usage of Microsoft in ::winrt::Microsoft::UI::Xaml::Controls::WebView2

I'm not sure what's exactly going wrong and can't find something similar to my issue. Would anybody know what's missing/needs to be changed to get the sample working?


Solution

  • Errors in creating a Webview2 sample app in UWP

    As Raymond Chen points out the code is failing to include the C++/WinRT projection headers for Microsoft::UI::Xaml::Controls. After installing the NuGet package, please go to pch.h and add the following #include directives. For more info you could refer to A basic C++/WinRT Windows UI Library 2 example (UWP) document.

    #include "winrt/Microsoft.UI.Xaml.Automation.Peers.h"
    #include "winrt/Microsoft.UI.Xaml.Controls.h"
    #include "winrt/Microsoft.UI.Xaml.Controls.Primitives.h"
    #include "winrt/Microsoft.UI.Xaml.Media.h"
    #include "winrt/Microsoft.UI.Xaml.XamlTypeInfo.h"