Xamarin Forms - WebView未显示出来

9
我正在开发一个小型的Xamarin.Forms Webview应用程序。这是对之前回答的一个问题的追问:xamarin-forms-making-webview-go-back 所以我已经实现并成功使用了一个工具栏和后退按钮。但是当我在模拟器已经开启的情况下运行程序(我使用的是Genymotion),程序会运行并显示出工具栏和后退按钮...但是没有任何Webview内容显示。
但是奇怪的是,有时候当我在模拟器处于睡眠状态时运行程序,然后重新打开模拟器,程序就可以完美地运行。此外,当我在iOS上进行测试时,它只显示工具栏,而没有Webview!更多时候,模拟器不会显示Webview。我还在我的Android设备上进行了测试,结果也一样,会显示工具栏但不会显示Webview。
可能有点令人困惑,但有人能帮我解决这个问题吗?
下面是我的代码: App.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Xamarin.Forms;

namespace WebView_form
{
    public class App : Application
    {
        public App()
        {
            //const string URL = "http://www.google.com";
            MainPage = new NavigationPage(new WebPage());
        }

        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }
}

WebPage.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;

using Xamarin.Forms;

namespace WebView_form
{
    public class WebPage : ContentPage
    {
        private WebView webView;

        public WebPage()
        {
            webView = new WebView 
            {
                Source = "https://www.google.com"
            };


            // toolbar
            ToolbarItems.Add(new ToolbarItem("Back", null, () =>
                {
                    webView.GoBack();
                }));

            Content = new StackLayout
            {
                Children = { webView }
            };
        }
    }
}

如果有人能帮我,那就太好了。

3个回答

20

如果设置VerticalOptionsFillAndExpand后仍无法解决问题,请对HorizontalOptions执行同样的操作。

可能是因为当布局发生时,WebView仍然是空的,导致其高度为零。

因此,请按以下方式更改WebPage.cs中的代码:

// ... Other code

public WebPage()
{
  webView = new WebView 
  {
     Source = "https://www.google.com",
     VerticalOptions = LayoutOptions.FillAndExpand,
     HorizontalOptions = LayoutOptions.FillAndExpand
  };


  // toolbar
  ToolbarItems.Add(new ToolbarItem("Back", null, () =>
  {
     webView.GoBack();
  }));

  Content = new StackLayout
  {
     Children = { webView }
  };
}

// ... Other code

2

另一件需要考虑的事情是:如果您正在响应 WebView.Navigating 事件,请确保在加载 WevView.Source 页面时不将其 args.Cancel 设置为 true。WebView.Navigating 的 iOS 实现会在加载 WebView.Source 时触发,但 Android 实现不会。如果您在问题页面为 WebView.Source 时将 args.Cancel 设置为 true,则 WebView 将为空白。


1
你能更好地解释一下你的想法吗? - Alessandro Caliaro

0

不建议这样做!不要允许非HTTPs加载。很可能您正在使用自签名证书,因此被阻止了。 - eltiare

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接