An old question, but I find accepted answer an absolute overkill. You don't need to parse the formatted text at all! Just wrap it up in Span
element and you are done.
public class Attached
{
public static readonly DependencyProperty FormattedTextProperty = DependencyProperty.RegisterAttached(
"FormattedText",
typeof(string),
typeof(Attached),
new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.AffectsMeasure, FormattedTextPropertyChanged));
public static void SetFormattedText(DependencyObject textBlock, string value)
{
textBlock.SetValue(FormattedTextProperty, value);
}
public static string GetFormattedText(DependencyObject textBlock)
{
return (string)textBlock.GetValue(FormattedTextProperty);
}
private static void FormattedTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var textBlock = d as TextBlock;
if (textBlock == null)
{
return;
}
var formattedText = (string)e.NewValue ?? string.Empty;
formattedText = string.Format("<Span xml:space="preserve" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">{0}</Span>", formattedText);
textBlock.Inlines.Clear();
using (var xmlReader = XmlReader.Create(new StringReader(formattedText)))
{
var result = (Span)XamlReader.Load(xmlReader);
textBlock.Inlines.Add(result);
}
}
}
Now you can use the FormattedText
attached property either in your code:
string inlineExpression = "<Run Style="Theme.GrayText">Once I saw a little bird, go hop, hop, hop.</Run>";
Attached.SetFormattedText(myTextBlock1, inlineExpression);
More importantly, straight from the XAML:
<TextBlock ns:Attached.FormattedText="{Binding Content}" />
Where ns
is the namespace you defined the Attached
class in.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…