微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

适用于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.
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>

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

原文地址:https://www.jb51.cc/windows/364239.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐