Another version of this is not quite the same as format recognition here, but here is a class for automatically recognizing links in a piece of text and turning them into live hyperlinks:
internal class TextBlockExt { static Regex _regex = new Regex(@"http[s]?://[^\s-]+", RegexOptions.Compiled); public static readonly DependencyProperty FormattedTextProperty = DependencyProperty.RegisterAttached("FormattedText", typeof(string), typeof(TextBlockExt), 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); } static void FormattedTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (!(d is TextBlock textBlock)) return; var formattedText = (string)e.NewValue ?? string.Empty; string fullText = $"<Span xml:space=\"preserve\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">{formattedText}</Span>"; textBlock.Inlines.Clear(); using (var xmlReader1 = XmlReader.Create(new StringReader(fullText))) { try { var result = (Span)XamlReader.Load(xmlReader1); RecognizeHyperlinks(result); textBlock.Inlines.Add(result); } catch { formattedText = System.Security.SecurityElement.Escape(formattedText); fullText = $"<Span xml:space=\"preserve\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">{formattedText}</Span>"; using (var xmlReader2 = XmlReader.Create(new StringReader(fullText))) { try { dynamic result = (Span) XamlReader.Load(xmlReader2); textBlock.Inlines.Add(result); } catch {
Using this, you can simply do <TextBlock ns:Attached.FormattedText="{Binding Content}"/>
instead of <TextBlock Text="{Binding Content}"/>
and it will automatically recognize and activate links, as well as recognize regular tags formatting such as <Bold>
etc.
Please note that this is based on @gwiazdorrr's answer here, as well as some other answers to this question; I basically combined them all in 1 and did some recursion processing, and it works! :). Templates and systems can also be adapted to recognize other types of links or markup, if necessary.
source share