Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I show HTML inside a Xamarin.Forms page with source for HTML in C#?

I wrote this code to try and show a couple of lines of HTML within a web page:

I have this XAML:

 <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
    xmlns:local="clr-namespace:Japanese;assembly=Test" 
    x:Class="Test.HelpCards" 
    x:Name="HelpCards" 
    Title="Help ▹ Cards Tab">
    <ContentPage.Content>
        <ScrollView>
            <StackLayout Spacing="10" Margin="20">
               <WebView x:Name="Browser" />
            </StackLayout>
        </ScrollView>
    </ContentPage.Content>
</ContentPage>

    public HelpCards()
    {
        InitializeComponent();
        var htmlSource = new HtmlWebViewSource();
        htmlSource.Html = @"<html><body>
        <h1>ABC</h1>
        <p>DEF</p>
        </body></html>";
        Browser.Source = htmlSource;
    }

However when running the code I see only a blank page.

Does anyone have any ideas as to what might be wrong?

like image 966
Alan2 Avatar asked Oct 25 '17 14:10

Alan2


2 Answers

Make sure to specify layout-options for WebView.

<ContentPage.Content>
    <ScrollView> <!-- ScrollView not needed as WebView has inbuilt scrolling behavior -->
        <StackLayout Spacing="10" Margin="20">
           <WebView x:Name="Browser" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" />
        </StackLayout>
    </ScrollView>
</ContentPage.Content>
like image 169
Sharada Gururaj Avatar answered Jan 03 '23 00:01

Sharada Gururaj


The webview can be in the ContentPage.Content by itself. No need to wrap it in a ScrollView or StackLayout. This method also doesn't require Horizontal or Vetical Options to be specified as well.

<ContentPage.Content>
    <WebView x:Name="Browser" />
</ContentPage.Content>
like image 27
heinst Avatar answered Jan 03 '23 02:01

heinst