Sahesh
Sahesh

Reputation: 885

XAML WebView binding to string not working in Xamarin Forms

I'm new to C# and Xamarin Forms. I'm having a webview and getting source url from an API. (For this question , I have hardcode the value). I binded source url instead of adding the value to Source in XAML. But it's not working. There are few solutions in stack and forums. I tried. But didn't work. Someone please help me to sovle this.

This is my 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>

This is how I bind the source. (Tried this in Codebehind and ViewModel too)

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

Upvotes: 2

Views: 2210

Answers (1)

Gerald Versluis
Gerald Versluis

Reputation: 34103

You're using it wrong, when using the HtmlWebViewSource you need to specify actual HTML instead of the URL where you want to go to. If you want to navigate to a URL, specify it in the Source property.

If you want to bind it, you have to implement something like this.

In your view model create a string property:

public string UrlToGoTo { get; set; }

Then set it like you normally would, make sure to have INotifyPropertyChanged is implemented somehow.

Then, wire up your WebView like this:

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

Upvotes: 4

Related Questions