TextBlock Windows Phone 8.1中的文本格式

Rom*_*iri 1 c# windows-phone-8 windows-store-apps windows-phone-8.1

我有一个字符串列表,ViewModel格式如下:

 This is an <b>example.<b>
Run Code Online (Sandbox Code Playgroud)

我希望在我的视图中有一些文本控件,它将通过DataBinding*显示格式化文本,如下所示:

这是一个例子.

我找不到任何可以表现得像这样的内置控件.

有谁知道如何处理它?

Rom*_*asz 5

你可以使用Run:

<TextBlock FontSize="30">
    <Run>This is an</Run>
    <Run FontWeight="Bold" Text=" example"/>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)

为此,您必须解析字符串,选择粗体部分,并在后面的代码中定义内容.一个非常简单的示例可能如下所示:

string example = @"This is an <b>example.</b>";
var str = example.Split(new string[] { "<b>", "</b>" }, StringSplitOptions.None);
for (int i = 0; i < str.Length; i++)
    myTextBlock.Inlines.Add(new Run { Text = str[i], FontWeight = i % 2 == 1 ? FontWeights.Bold : FontWeights.Normal });
Run Code Online (Sandbox Code Playgroud)

编辑 - 使用绑定

如果你想在Binding上使用上面的过程,那就不那么简单了 - TextBlock.Inlines不是DependencyProperty,所以我们不能使用它.然而有一种方法可以做到这一点 - 你需要以某种方式扩展你的TextBlock - 这是另一个陷阱 - 它是密封的类,所以没有继承.在这种情况下,我们将不得不使用另一个类(这也是一个很好的例子):

public static class TextBlockExtension
{
    public static string GetFormattedText(DependencyObject obj)
    { return (string)obj.GetValue(FormattedTextProperty); }

    public static void SetFormattedText(DependencyObject obj, string value)
    { obj.SetValue(FormattedTextProperty, value); }

    public static readonly DependencyProperty FormattedTextProperty =
        DependencyProperty.Register("FormattedText", typeof(string), typeof(TextBlockExtension),
        new PropertyMetadata(string.Empty, (sender, e) =>
        {
            string text = e.NewValue as string;
            var textBl = sender as TextBlock;
            if (textBl != null)
            {
                textBl.Inlines.Clear();
                var str = text.Split(new string[] { "<b>", "</b>" }, StringSplitOptions.None);
                for (int i = 0; i < str.Length; i++)
                    textBl.Inlines.Add(new Run { Text = str[i], FontWeight = i % 2 == 1 ? FontWeights.Bold : FontWeights.Normal });
            }
        }));
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样在xaml中使用它:

<TextBlock local:TextBlockExtension.FormattedText="{Binding MyText}"/>
Run Code Online (Sandbox Code Playgroud)