适用于Windows Phone 7的HTMLTextBlock

前端之家收集整理的这篇文章主要介绍了适用于Windows Phone 7的HTMLTextBlock前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在我的 Windows Phone 7中包含一个html文本框.我看到一些 sample code here.问题是Windows Phone 7中不存在HTMLPage类,或者更确切地说,System.Windows.Browser不存在.有人知道替代方案吗?
出于同样的原因,我在努力解决这个问题,并最终想出了一个解决方案.我需要在我的 Septic’s Companion app的ListBox显示一堆这些.现在我的解决方案只处理粗体或斜体(因为这是我所关心的)但是很容易修改它来处理更多.首先,在我的viewmodel中,我编写了一个例程,在给定HTML字符串的情况下返回TextBlock.
  1. private TextBlock MakeFormattedTextBlock(string shtml)
  2. {
  3. TextBlock tb = new TextBlock();
  4. Run temprun = new Run();
  5.  
  6. int bold = 0;
  7. int italic = 0;
  8.  
  9. do
  10. {
  11. if ((shtml.StartsWith("<b>")) | (shtml.StartsWith("<i>")) |
  12. (shtml.StartsWith("</b>")) | (shtml.StartsWith("</i>")))
  13. {
  14. bold += (shtml.StartsWith("<b>") ? 1 : 0);
  15. italic += (shtml.StartsWith("<i>") ? 1 : 0);
  16. bold -= (shtml.StartsWith("</b>") ? 1 : 0);
  17. italic -= (shtml.StartsWith("</i>") ? 1 : 0);
  18. shtml = shtml.Remove(0,shtml.IndexOf('>') + 1);
  19. if (temprun.Text != null)
  20. tb.Inlines.Add(temprun);
  21. temprun = new Run();
  22. temprun.FontWeight = ((bold > 0) ? FontWeights.Bold : FontWeights.Normal);
  23. temprun.FontStyle = ((italic > 0) ? FontStyles.Italic : FontStyles.Normal);
  24. }
  25. else // just a piece of plain text
  26. {
  27. int nextformatthing = shtml.IndexOf('<');
  28. if (nextformatthing < 0) // there isn't any more formatting
  29. nextformatthing = shtml.Length;
  30. temprun.Text += shtml.Substring(0,nextformatthing);
  31. shtml = shtml.Remove(0,nextformatthing);
  32. }
  33. } while (shtml.Length > 0);
  34. // Flush the last buffer
  35. if (temprun.Text != null)
  36. tb.Inlines.Add(temprun);
  37. return tb;
  38. }

然后我只需要一种方法将其构建到我的XAML中.这可能不是最好的解决方案,但是我首先做了另一个例程来返回一个包含TextBlock的StackPanel和我想要的文本.

  1. public StackPanel WordBlock
  2. {
  3. get
  4. {
  5. StackPanel sp = new StackPanel();
  6. TextBlock tbWord = MakeFormattedTextBlock("<b>" + Word + "</b>: " + Desc);
  7. sp.Children.Add(tbWord);
  8. return sp;
  9. }
  10. }

为了将它绑定到一个可见的控件,我然后为我的ListBox创建了一个DataTemplate,它只是从我的视图模型中读取整个StackPanel.

  1. <DataTemplate x:Key="WordInList2">
  2. <ContentControl Content="{Binding WordBlock}"/>
  3. </DataTemplate>

正如我所说的,可能有一些部分并没有像它们那样优雅地完成,但这样做了我想要的.希望这对你有用!

猜你在找的Windows相关文章