Reputation: 71
I have a textblock which binds to a string from a datasource. The string, however, is html formatted (it has <p>
and <a href>
tags).
I want to be able to display the formatted string using binding, so I don't want to manipulate it in code outside of converters. Is there a way to do this with a RichTextBox
, or some other control?
Upvotes: 1
Views: 600
Reputation: 1685
You could host a WebBrowser
control and display the HTML with the NavigateToString
method.
If you want to use MVVM and data binding, here is an attached property I created for exactly the same use case.
public static class WebBrowserExtensions
{
public static readonly DependencyProperty HtmlProperty =
DependencyProperty.RegisterAttached(
"Html",
typeof(string),
typeof(WebBrowserExtensions),
new PropertyMetadata(null, OnHtmlChanged));
public static void SetHtml(WebBrowser webBrowser, string html)
{
webBrowser.SetValue(HtmlProperty, html);
}
public static string GetHtml(WebBrowser webBrowser)
{
return (string)webBrowser.GetValue(HtmlProperty);
}
private static void OnHtmlChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
var webBrowser = (WebBrowser)sender;
if (webBrowser != null)
{
var body = GetHtml(webBrowser);
var style = "<style>";
var background = "white";
var foreground = "black";
style += "body{background-color: " + background + "; color: " + foreground + ";}";
style += "</style>";
var html = "<!DOCTYPE html><html><head>" + style + "</head><body>" + body + "</body></html>";
webBrowser.NavigateToString(html);
}
}
}
You can then use it like this:
<phone:WebBrowser
local:WebBrowserExtensions.Html="{Binding Path=Text}" />
Upvotes: 0
Reputation: 16369
Try HTMLTextBox
from the MSP Toolkit, it works quite well for such scenarios.
Upvotes: 2