适用于 Windows Phone 7 的 HTMLTextBlock

标签 html silverlight windows-phone-7

我正在尝试将 html 文本框包含到我的 Windows Phone 7 中。我看到了一些 sample code here .问题是 HTMLPage 类在 Windows Phone 7 中不存在,或者更确切地说,System.Windows.Browser 不存在。有人知道这个的替代方案吗?

最佳答案

出于同样的原因,我为此苦苦挣扎,最终想出了一个解决方案。我需要在我的 Septic's Companion app 的列表框中显示这些内容.现在我的解决方案只处理粗体或斜体(因为这是我所关心的)但修改它以处理更多内容很容易。首先,在我的 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 中的方法。这可能不是最好的解决方案,但我首先创建了另一个例程来返回一个 StackPanel,其中包含带有我想要的文本的 TextBlock。

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

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

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

正如我所说,其中可能有些部分没有像它们可能的那样优雅地完成,但这达到了我想要的效果。希望它对你有用!

关于适用于 Windows Phone 7 的 HTMLTextBlock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4505642/

相关文章:

Silverlight 2如何知道所有ASYNC WCF调用已经完成

visual-studio-2010 - 如何修复值不能为空参数名称 : typeName when opening XAML file?

银光 4 : Chart Control

wcf - 服务端点错误

silverlight - WP7 墓碑 - 用户期望?

javascript - 将默认选项卡设置为 Angular.js 选项卡

javascript - 如何获得div的顶级父级

javascript - 表单与 post 方法到谷歌电子表格不再工作

c# - WP7——在我的计算机上查找isolatedStorage文件

javascript - 使用 JS 从不同的 html 文件访问 DOM