适用于Windows Phone 7的HTMLTextBlock

vod*_*ang 6 html silverlight windows-phone-7

我试图在我的Windows Phone 7中包含一个html文本框.我在这里看到一些示例代码.问题是Windows Phone 7中不存在HTMLPage类,或者更确切地说,System.Windows.Browser不存在.有人知道替代方案吗?

Chr*_*Rae 6

出于同样的原因,我在努力解决这个问题,并最终想出了一个解决方案.我需要在ListBox中为我的Septic's Companion应用程序显示一堆这些内容.现在我的解决方案只处理粗体或斜体(因为这是我所关心的)但是很容易修改它来处理更多.首先,在我的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;
}
Run Code Online (Sandbox Code Playgroud)

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

public StackPanel WordBlock
{
    get
    {
        StackPanel sp = new StackPanel();
        TextBlock tbWord = MakeFormattedTextBlock("<b>" + Word + "</b>: " + Desc);
        sp.Children.Add(tbWord);
        return sp;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

<DataTemplate x:Key="WordInList2">
    <ContentControl Content="{Binding WordBlock}"/>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)

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


Ter*_*nce 6

嘿,我将SilverlightHtmlTextBlock转换为WP7 .我没有对非常复杂的情况进行测试,并且在dtd标签上爆炸但是,它可以完成更简单的html案例,听起来就像你在寻找的那样.