David Clarke
David Clarke

Reputation: 13266

XAML WebView binding to HTML source not working

I have a XAML page layout defined that includes a WebView populated from an HTML string:

<WebView HorizontalOptions="Fill" VerticalOptions="FillAndExpand">
    <WebView.Source>
        <HtmlWebViewSource Html="{Binding Flag.Description}" />
<!--    <HtmlWebViewSource Html="&lt;html>&lt;body>&lt;p>The HTML string.&lt;/p>&lt;/body>&lt;/html>" />-->
    </WebView.Source>
</WebView>

When I hard code the string into the XAML it displays correctly, but it will not bind to the Flag.Description string. The XAML includes a couple of labels that bind correctly but I can't find any reason why the WebView source isn't binding correctly.

Upvotes: 4

Views: 11392

Answers (5)

Justice Rakgwale
Justice Rakgwale

Reputation: 1

public HtmlWebViewSource Description { get { var webView = "html content";return
 new HtmlWebViewSource { Html = webView };} }
<WebView
  HorizontalOptions="Fill"
  VerticalOptions="FillAndExpand"
  Source="{Binding Description}" />

Upvotes: 0

user6911715
user6911715

Reputation:

Would Flag or Flag.Description ever return null to the WebView? I was having the same problem and it turns out that the default value for my source was null before I initialized it with proper content. The WebView would essentially crashed. When I changed the null to String.Empty, it would work.

Upvotes: 0

James Wierzba
James Wierzba

Reputation: 17568

The accepted answer worked for me but I will add that it only works when you specify a height and width.

There are a few combinations that worked:

1. define HeightRequest and WidthRequest

<WebView Source="{Binding HtmlSource}" HeightRequest="300" WidthRequest="250" />

2. define HorizontalOptions and VerticalOptions

<WebView x:Name="WebViewTermsOfService" Source="{Binding HtmlSource}" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" />

However, when I specifed CenterAndExpand as a value, the HTML did not render

Upvotes: 3

David Clarke
David Clarke

Reputation: 13266

I wasn't able to get the binding to work in XAML but there is a code-based solution to the problem. I'm using FreshMvvm so in the page model (not the code-behind for the XAML page) I created a new property that references the HTML string:

public HtmlWebViewSource WebViewSource
{
    get { 
        return new HtmlWebViewSource { Html = Flag.Description }; 
    }
}

And the WebView element in the XAML page becomes:

<WebView
    HorizontalOptions="Fill"
    VerticalOptions="FillAndExpand"
    Source="{Binding WebViewSource}" />

Upvotes: 10

Sreeraj
Sreeraj

Reputation: 2434

Seems like Binding Html property for HtmlWebViewSource just won't work out of the box. I think a IValueConverter will do the job. Please have a look how it is done in this answer. I think that should be enough

Upvotes: 0

Related Questions