【问题标题】:Windows Phone display formatted text using binding in xamlWindows Phone 使用 xaml 中的绑定显示格式化文本
【发布时间】:2014-02-14 06:25:58
【问题描述】:

我有一个文本块,它绑定到来自数据源的字符串。但是,该字符串是 html 格式的(它有 <p><a href> 标签)。

我希望能够使用绑定显示格式化的字符串,所以我不想在转换器之外的代码中对其进行操作。有没有办法通过RichTextBox 或其他控件来做到这一点?

【问题讨论】:

    标签: silverlight xaml windows-phone-8 windows-phone


    【解决方案1】:

    MSP Toolkit 中尝试HTMLTextBox,它非常适合这种情况。

    【讨论】:

      【解决方案2】:

      您可以托管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}" />
      

      【讨论】:

      • 感谢您的回复!看来 OnHtmlChanged 方法的格式正确,但我在实际的 WebBrowser 上看不到任何内容。我是否错过了 WebBrowser 上的某些内容以使其显示?
      • 我的错,是别的。这似乎很完美!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-30
      • 2013-06-08
      • 1970-01-01
      • 2011-01-18
      • 2023-03-06
      相关资源
      最近更新 更多