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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With