首页 > 解决方案 > XAML WebView 绑定到字符串在 Xamarin 表单中不起作用

问题描述

我是 C# 和 Xamarin 表单的新手。我有一个 webview 并从 API 获取源 URL。(对于这个问题,我对值进行了硬编码)。我绑定了源 url,而不是在 XAML 中将值添加到 Source。但它不起作用。堆栈和论坛中的解决方案很少。我试过了。但是没有用。有人请帮我解决这个问题。

这是我的 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" x:Class="MyProject.Views.NewRegistration.PrivacyWebView">
    <ContentPage.Content>
        <AbsoluteLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
            <WebView Source="{Binding WebViewSource}" HeightRequest= "300" WidthRequest="250" Navigated="Handle_Navigated" VerticalOptions="FillAndExpand" AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds="0,0,1,1" />
            <ActivityIndicator x:Name="loader" IsRunning="true" IsVisible="true" AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds="0,0,1,1"/>
        </AbsoluteLayout>
    </ContentPage.Content>
</ContentPage>

这就是我绑定源的方式。(也在 Codebehind 和 ViewModel 中尝试过)

 public HtmlWebViewSource WebViewSource
{
    get
    {
        return new HtmlWebViewSource { Html = "https://www.stackoverflow.com" };
    }
}  

标签: c#xamarinwebviewxamarin.forms

解决方案


你用错了,在使用时HtmlWebViewSource你需要指定实际的 HTML 而不是你想去的 URL。如果要导航到 URL,请在Source属性中指定它。

如果你想绑定它,你必须实现这样的东西。

在您的视图模型中创建一个字符串属性:

public string UrlToGoTo { get; set; }

然后像往常一样设置它,确保以INotifyPropertyChanged某种方式实现。

然后,WebView像这样连接你的:

<WebView Source="{Binding UrlToGoTo}"
    HeightRequest= "300"
    WidthRequest="250"
    Navigated="Handle_Navigated"
    VerticalOptions="FillAndExpand"
    AbsoluteLayout.LayoutFlags="All"
    AbsoluteLayout.LayoutBounds="0,0,1,1" />

推荐阅读