Binding HTML string to Webview

Ronald Rex 181 Reputation points
2022-12-28T14:34:45.297+00:00

Hi Friends. Using the XAML below I can show a webview with hard coded HTML. But what if I wanted to bind the HTML to the webview so that I could dynamically update the webview. I have tried following numerous discussions involving the webview to figure out how to make it work, but no success. I am trying to get this to work in a .Net Maui application Any help would be greatly appreciated.

 <WebView HeightRequest="100" WidthRequest="200">  
                    <WebView.Source>  
                        <HtmlWebViewSource>  
                            <HtmlWebViewSource.Html>  
                                <![CDATA[  
                                <HTML>  
                                <BODY>  
                                <H1>.NET MAUI</H1>  
                                <P>Welcome to WebView.</P>  
                                </BODY>  
                                </HTML>  
                             ]]>  
                            </HtmlWebViewSource.Html>  
                        </HtmlWebViewSource>  
                    </WebView.Source>  
    </WebView>  
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,900 questions
0 comments No comments
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 35,806 Reputation points Microsoft Vendor
    2022-12-29T05:13:07.79+00:00

    Hello,

    You could binding HTML string to Webview via Source property.

    Please refer to the following code sample:

       // in your ViewModel  
       public HtmlWebViewSource HtmlWebViewSource {  
       get { return htmlWebViewSource; }  
       set { SetProperty(ref htmlWebViewSource, value); } }  
         
       private HtmlWebViewSource htmlWebViewSource;  
         
         
       // Set Html content in ViewModel  
       HtmlWebViewSource = new HtmlWebViewSource  
       {  
             Html = @"<HTML><BODY><H1>.NET MAUI</H1><P>Welcome to WebView.</P></BODY></HTML>"  
       };  
         
         
       // use the binding HTML content  
       <WebView HeightRequest="100" WidthRequest="200" Source="{Binding HtmlWebViewSource}">  
       </WebView>  
    

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful