首页 > 解决方案 > Xamarin 表单绑定 Webview 在 Android 上显示,但不在 IOS 上从等待的任务中显示

问题描述

我创建了一个新的 Xamarin Forms Prism 项目来复制我在实际应用中遇到的这个问题。我想去我的数据/网络服务并获取我的应用程序首页的公告。它只是一个 HTML 字符串,所以我使用的是 WebView,我的 MainPage.xaml 看起来像 .

<?xml version="1.0" encoding="utf-8" ?>

<StackLayout HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand">
<Button Text="Go to page 1" Command="{Binding NextPageCommand}"/>
<WebView x:Name="webView"  WidthRequest="1000" HeightRequest="1000" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
    <WebView.Source>
        <HtmlWebViewSource Html="{Binding Announcements}"/>
    </WebView.Source>
</WebView>
</StackLayout>

还有我的 ViewModel

using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BlankApp1.ViewModels
{
    public class MainPageViewModel : ViewModelBase,INavigatedAware
    {
    public MainPageViewModel(INavigationService navigationService) 
    : base (navigationService)
    {
        Title = "Main Page";
        NextPageCommand = new DelegateCommand(NextPage);
    }
    public DelegateCommand NextPageCommand { get; }
    private string _announcements;
    public string Announcements
    {
        get { return _announcements; }
        set { SetProperty(ref _announcements, value); }

    }
    private async void NextPage()
    {
        await NavigationService.NavigateAsync("Page1");

    }
    public async void OnNavigatedTo(NavigationParameters parameters)
    {

        if (Announcements == null)
        {
            Announcements = "<html><body>" + "Working Shows this HTML in the Webview" + "</body></html>";
        }
        else
        {
            Announcements = "<html><body>" + "Not Working, Didnt update with this new HTML" + "</body></html>";
        }

    }        
    public async void OnNavigatedFrom(NavigationParameters parameters)
    {
        //throw new NotImplementedException();
    }
}

}

在 OnNavgatedTo 函数中,它不会更新当您离开此页面然后返回时显示的 HTML。

如果有人知道为什么这可能在 android 上运行良好但在 iOS 上运行良好,请告诉我。我已经看了 2 天了,仍然无法像在 Android 上那样显示它

标签: iosxamarinwebviewxamarin.formsprism

解决方案


如果要更改 WebView 的内容,请尝试绑定其HtmlWebViewSource而不是Html.

在您的视图模型中创建您的HtmlWebViewSource属性:

private HtmlWebViewSource _webviewSource;
public HtmlWebViewSource WebviewSource
{
    get { return _webviewSource; }
    set
    {
        SetProperty(ref _webviewSource, value);
    }
}

然后像这样绑定它:

<WebView x:Name="webView"  WidthRequest="1000" HeightRequest="1000" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Source="{Binding WebviewSource}">

当你想改变它时,试试这个:

if (WebviewSource == null)
{
    WebviewSource = new HtmlWebViewSource { Html = "<html><body>" + "Working Shows this HTML in the Webview" + "</body></html>" };
}
else
{
    WebviewSource = new HtmlWebViewSource { Html = "<html><body>" + "Not Working, Didnt update with this new HTML" + "</body></html>" };
}

推荐阅读