Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>How about using attached behavior? Below code only handles bold tags. Each word which should be bold needs to be wrapped in bold tags. You probably want to make the class accept other formats as well. Also spaces needs to be handled better, the class strips out consecutive spaces and add one extra to the end. So consider below class as demo code only which will need further work to be useful but it should get you started. </p> <p>XAML:</p> <pre><code>&lt;Window x:Class="FormatTest.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:FormatTest="clr-namespace:FormatTest" Title="Window1" Height="300" Width="300"&gt; &lt;TextBlock FormatTest:FormattedTextBehavior.FormattedText="{Binding Path=Text}" /&gt; &lt;/Window&gt; </code></pre> <p>Code behind:</p> <pre><code>using System; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; namespace FormatTest { public partial class Window1 : Window { public Window1() { InitializeComponent(); DataContext = this; } public string Text { get { return "Some &lt;Bold&gt;formatted&lt;/Bold&gt; text."; } } } public static class FormattedTextBehavior { 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.RegisterAttached("FormattedText", typeof(string), typeof(FormattedTextBehavior), new UIPropertyMetadata("", FormattedTextChanged)); private static void FormattedTextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { TextBlock textBlock = sender as TextBlock; string value = e.NewValue as string; string[] tokens = value.Split(' '); foreach (string token in tokens) { if (token.StartsWith("&lt;Bold&gt;") &amp;&amp; token.EndsWith("&lt;/Bold&gt;")) { textBlock.Inlines.Add(new Bold(new Run(token.Replace("&lt;Bold&gt;", "").Replace("&lt;/Bold&gt;", "") + " "))); } else { textBlock.Inlines.Add(new Run(token + " ")); } } } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload