我试图在我的
Windows Phone 7中包含一个html文本框.我看到一些
sample code here.问题是Windows Phone 7中不存在HTMLPage类,或者更确切地说,System.Windows.Browser不存在.有人知道替代方案吗?
出于同样的原因,我在努力解决这个问题,并最终想出了一个解决方案.我需要在我的
Septic’s Companion app的ListBox中显示一堆这些.现在我的解决方案只处理粗体或斜体(因为这是我所关心的)但是很容易修改它来处理更多.首先,在我的viewmodel中,我编写了一个例程,在给定HTML字符串的情况下返回TextBlock.
- private TextBlock MakeFormattedTextBlock(string shtml)
- {
- TextBlock tb = new TextBlock();
- Run temprun = new Run();
- int bold = 0;
- int italic = 0;
- do
- {
- if ((shtml.StartsWith("<b>")) | (shtml.StartsWith("<i>")) |
- (shtml.StartsWith("</b>")) | (shtml.StartsWith("</i>")))
- {
- bold += (shtml.StartsWith("<b>") ? 1 : 0);
- italic += (shtml.StartsWith("<i>") ? 1 : 0);
- bold -= (shtml.StartsWith("</b>") ? 1 : 0);
- italic -= (shtml.StartsWith("</i>") ? 1 : 0);
- shtml = shtml.Remove(0,shtml.IndexOf('>') + 1);
- if (temprun.Text != null)
- tb.Inlines.Add(temprun);
- temprun = new Run();
- temprun.FontWeight = ((bold > 0) ? FontWeights.Bold : FontWeights.Normal);
- temprun.FontStyle = ((italic > 0) ? FontStyles.Italic : FontStyles.Normal);
- }
- else // just a piece of plain text
- {
- int nextformatthing = shtml.IndexOf('<');
- if (nextformatthing < 0) // there isn't any more formatting
- nextformatthing = shtml.Length;
- temprun.Text += shtml.Substring(0,nextformatthing);
- shtml = shtml.Remove(0,nextformatthing);
- }
- } while (shtml.Length > 0);
- // Flush the last buffer
- if (temprun.Text != null)
- tb.Inlines.Add(temprun);
- return tb;
- }
然后我只需要一种方法将其构建到我的XAML中.这可能不是最好的解决方案,但是我首先做了另一个例程来返回一个包含TextBlock的StackPanel和我想要的文本.
- public StackPanel WordBlock
- {
- get
- {
- StackPanel sp = new StackPanel();
- TextBlock tbWord = MakeFormattedTextBlock("<b>" + Word + "</b>: " + Desc);
- sp.Children.Add(tbWord);
- return sp;
- }
- }
为了将它绑定到一个可见的控件,我然后为我的ListBox创建了一个DataTemplate,它只是从我的视图模型中读取整个StackPanel.
- <DataTemplate x:Key="WordInList2">
- <ContentControl Content="{Binding WordBlock}"/>
- </DataTemplate>
正如我所说的,可能有一些部分并没有像它们那样优雅地完成,但这样做了我想要的.希望这对你有用!