【发布时间】:2014-02-14 06:25:58
【问题描述】:
我有一个文本块,它绑定到来自数据源的字符串。但是,该字符串是 html 格式的(它有 <p> 和 <a href> 标签)。
我希望能够使用绑定显示格式化的字符串,所以我不想在转换器之外的代码中对其进行操作。有没有办法通过RichTextBox 或其他控件来做到这一点?
【问题讨论】:
标签: silverlight xaml windows-phone-8 windows-phone
我有一个文本块,它绑定到来自数据源的字符串。但是,该字符串是 html 格式的(它有 <p> 和 <a href> 标签)。
我希望能够使用绑定显示格式化的字符串,所以我不想在转换器之外的代码中对其进行操作。有没有办法通过RichTextBox 或其他控件来做到这一点?
【问题讨论】:
标签: silverlight xaml windows-phone-8 windows-phone
从MSP Toolkit 中尝试HTMLTextBox,它非常适合这种情况。
【讨论】:
您可以托管WebBrowser 控件并使用NavigateToString 方法显示HTML。
如果您想使用 MVVM 和数据绑定,这是我为完全相同的用例创建的附加属性。
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);
}
}
}
然后你可以像这样使用它:
<phone:WebBrowser
local:WebBrowserExtensions.Html="{Binding Path=Text}" />
【讨论】: