Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding html string content to Webview in xaml

Tags:

c#

xaml

webview

I have a webview in my xaml which looks as follows :

<WebView x:Name="WebView" />

And, in my codebehind I have a variable called "htmlcontent", which contains html string data which looks like as follows :

<html><body><b>Hi there</b></body></html>

How can I bind this html string and display it formatted in the webview component of the XAML?

*Edit - By the way, I am doing a Windows 8 metro application, so the WebBrowser control isn't supported

like image 886
MattTheHack Avatar asked Mar 19 '14 12:03

MattTheHack


1 Answers

The HtmlString property does not exist on WebView (only the Source property which is an Uri). But what you can do is to define yourself a new HtmlString attached property for WebView. Just create the following class :

namespace YOURNAMESPACE
{
    class MyProperties
    {
     // "HtmlString" attached property for a WebView
     public static readonly DependencyProperty HtmlStringProperty =
        DependencyProperty.RegisterAttached("HtmlString", typeof(string), typeof(MyProperties), new PropertyMetadata("", OnHtmlStringChanged));

     // Getter and Setter
     public static string GetHtmlString(DependencyObject obj) { return (string)obj.GetValue(HtmlStringProperty); }
     public static void SetHtmlString(DependencyObject obj, string value) { obj.SetValue(HtmlStringProperty, value); }

     // Handler for property changes in the DataContext : set the WebView
     private static void OnHtmlStringChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
     {
        WebView wv = d as WebView; 
        if (wv != null) 
        { 
            wv.NavigateToString((string)e.NewValue); 
        } 
     }
    }
}

Supposing that your DataContext field is called CurrentHtmlString, then you can use this new WebView's HtmlString property in your XAML file to bind it, with a syntax like :

 <WebView local:MyProperties.HtmlString="{Binding CurrentHtmlString}"></WebView>

Normally you already have the following line at the top of your XAML file :

xmlns:local="using:MYNAMESPACE"

You can find more explanation here from Rob Caplan : http://blogs.msdn.com/b/wsdevsol/archive/2013/09/26/binding-html-to-a-webview-with-attached-properties.aspx

like image 71
efdummy Avatar answered Nov 17 '22 14:11

efdummy