1
votes

I'm trying to display a WebView2 within a Xamarin WPF app on .NET 5.

So at startup I set the MainPage to Navigator which looks like so:

Navigator.xaml:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:XamTestNET5.Views"
             x:Class="XamTestNET5.Navigator" Title="Here is a title">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <StackLayout Grid.Row="0" Grid.Column="0" Orientation="Vertical" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
            <Label FontSize="Medium">Hello</Label>
            <!--<local:PlaceHolderView></local:PlaceHolderView>-->
            <local:CustomWebBrowserView x:Name="browser" Source="https://www.google.com"></local:CustomWebBrowserView>
        </StackLayout>
        <StackLayout Grid.Row="1" Grid.Column="0" Orientation="Horizontal" HorizontalOptions="FillAndExpand" BackgroundColor="{StaticResource Primary}">
            <Button FontSize="Large" Text="Tab 1" BorderWidth="0" BorderColor="Transparent"></Button>
            <Button FontSize="Large" Text="Tab 2" BorderWidth="0" BorderColor="Transparent"></Button>
            <Button FontSize="Large" Text="Tab 3" BorderWidth="0" BorderColor="Transparent"></Button>
        </StackLayout>
    </Grid>
</ContentPage>

CustomWebBrowserView.xaml:

<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="XamTestNET5.Views.CustomWebBrowserView">
  <ContentView.Content>
        <Grid></Grid>
  </ContentView.Content>
</ContentView>

CustomWebBrowserView.xaml.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace XamTestNET5.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class CustomWebBrowserView : ContentView
    {
        public static readonly BindableProperty SourceProperty = BindableProperty.Create(
          propertyName: "Source",
          returnType: typeof(string),
          declaringType: typeof(string),
          defaultValue: "");

        public string Source
        {
            get { return (string)GetValue(SourceProperty); }
            set { SetValue(SourceProperty, value); }
        }
        public CustomWebBrowserView()
        {
            InitializeComponent();
        }
    }
}

WebBrowserRenderer.cs in the WPF project:

using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.Wpf;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms.Platform.WPF;
using XamTestNET5.Views;
using XamTestNET5WPF.Renderers;

[assembly: ExportRenderer(typeof(CustomWebBrowserView), typeof(WebBrowserRenderer))]
namespace XamTestNET5WPF.Renderers
{
    public class WebBrowserRenderer : ViewRenderer<CustomWebBrowserView, WebView2>
    {
        WebView2 webView;
        CoreWebView2EnvironmentOptions options = new CoreWebView2EnvironmentOptions();
        CoreWebView2Environment env;
        String userDataFolder = Path.GetTempPath();

        public WebBrowserRenderer() : base()
        {
        }

        private void WebView_CoreWebView2Ready(object sender, EventArgs e)
        {
            this.webView.CoreWebView2.Navigate(@"https://www.bing.com");
        }

        protected async override void OnElementChanged(ElementChangedEventArgs<CustomWebBrowserView> e)
        {
            base.OnElementChanged(e);
            if (e.NewElement != null)
            {
                webView = new WebView2();
                env = await CoreWebView2Environment.CreateAsync("", userDataFolder, options);
                webView.CoreWebView2Ready += WebView_CoreWebView2Ready;
                webView.Source = new Uri(@"https://www.bing.com");
                webView.Visibility = System.Windows.Visibility.Visible;
                this.SetNativeControl(webView);
                await webView.EnsureCoreWebView2Async(env);
            }
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            if (e.PropertyName == nameof(CustomWebBrowserView.SourceProperty))
            {
                this.webView.Source = new Uri(Element.Source);
                this.webView.CoreWebView2.Navigate(Element.Source);
            }
        }
    }
}

I can see by debugging that I'm getting the WebView2 but it obliterates the content page leaving only the title.

If I comment out the CustomWebBrowserView and put in a PlaceHolderView stub, which just looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="XamTestNET5.Views.PlaceHolderView">
  <ContentView.Content>
      <StackLayout>
          <Label Text="Placeholder" />
      </StackLayout>
  </ContentView.Content>
</ContentView>

The layout at least isn't obliterated, but of course no WebView2.

I can't get Shell to work right either but that's to be expected: https://github.com/xamarin/Xamarin.Forms/issues/7377

So I thought that the workaround in the meantime might be just to create my own custom navigation within the app, but I want to provide WebView2 controls in WPF. Am I doing something wrong in the WebBrowserRenderer or Xaml?

1
Note: If I call this.webView.CoreWebView2.OpenDevToolsWindow(); from WebView_CoreWebView2Ready I do get the Dev Tools windows opened up to Bing, but I can't see the site rendered in the WPF View, and the WPF Page has been obliterated leaving only the Title.John Ernest

1 Answers

1
votes

Change CustomWebBrowserView to the following, basing off of View rather than ContentView and everything is working now with no obliteration of the view:

CustomWebBrowserView.Xaml:

<?xml version="1.0" encoding="UTF-8"?>
<View xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="XamTestNET5.Views.CustomWebBrowserView">
</View>

CustomWebBrowserView.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace XamTestNET5.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class CustomWebBrowserView : View
    {
        public static readonly BindableProperty SourceProperty = BindableProperty.Create(
          propertyName: "Source",
          returnType: typeof(string),
          declaringType: typeof(string),
          defaultValue: "");

        public string Source
        {
            get { return (string)GetValue(SourceProperty); }
            set { SetValue(SourceProperty, value); }
        }
        public CustomWebBrowserView()
        {
            InitializeComponent();
        }
    }
}

Navigator.xaml:

    <StackLayout Grid.Row="0" Grid.Column="0" Orientation="Vertical" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
        <Label FontSize="Medium">Hello</Label>
        <!--<local:PlaceHolderView></local:PlaceHolderView>-->
        <local:CustomWebBrowserView HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" x:Name="browser" Source="https://www.sneauxkones.com"></local:CustomWebBrowserView>
    </StackLayout>