[英]Text formatting in TextBlock Windows Phone 8.1
我的ViewModel
有以下格式的字符串列表:
This is an <b>example.<b>
我想在視圖中使用某種文本控件,它將通過DataBinding
*顯示格式化的文本,如下所示:
這是一個例子。
我找不到任何可以像這樣的內置控件。
有人知道如何處理嗎?
您可以使用Run :
<TextBlock FontSize="30">
<Run>This is an</Run>
<Run FontWeight="Bold" Text=" example"/>
</TextBlock>
為此,您將必須解析字符串,選擇粗體部分,然后在后面的代碼中定義內容。 一個非常簡單的示例如下所示:
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 });
編輯-與綁定一起使用
如果要對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 });
}
}));
}
然后,您可以像這樣在xaml中使用它:
<TextBlock local:TextBlockExtension.FormattedText="{Binding MyText}"/>
您可以使用RichTextBlock控件。 就像是:
<RichTextBlock>
<Paragraph>
This is an <Bold>example</Bold>
</Paragraph>
</RichTextBlock>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.