Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is my modified code for recursively format text. It handles Bold, Italic, Underline and LineBreak but can easily be extended to support more (modify the <strong>switch</strong> statement).</p> <pre class="lang-cs prettyprint-override"><code>public static class MyBehavior { 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(MyBehavior), new UIPropertyMetadata("", FormattedTextChanged)); static Inline Traverse(string value) { // Get the sections/inlines string[] sections = SplitIntoSections(value); // Check for grouping if (sections.Length.Equals(1)) { string section = sections[0]; string token; // E.g &lt;Bold&gt; int tokenStart, tokenEnd; // Where the token/section starts and ends. // Check for token if (GetTokenInfo(section, out token, out tokenStart, out tokenEnd)) { // Get the content to further examination string content = token.Length.Equals(tokenEnd - tokenStart) ? null : section.Substring(token.Length, section.Length - 1 - token.Length * 2); switch (token) { case "&lt;Bold&gt;": return new Bold(Traverse(content)); case "&lt;Italic&gt;": return new Italic(Traverse(content)); case "&lt;Underline&gt;": return new Underline(Traverse(content)); case "&lt;LineBreak/&gt;": return new LineBreak(); default: return new Run(section); } } else return new Run(section); } else // Group together { Span span = new Span(); foreach (string section in sections) span.Inlines.Add(Traverse(section)); return span; } } /// &lt;summary&gt; /// Examines the passed string and find the first token, where it begins and where it ends. /// &lt;/summary&gt; /// &lt;param name="value"&gt;The string to examine.&lt;/param&gt; /// &lt;param name="token"&gt;The found token.&lt;/param&gt; /// &lt;param name="startIndex"&gt;Where the token begins.&lt;/param&gt; /// &lt;param name="endIndex"&gt;Where the end-token ends.&lt;/param&gt; /// &lt;returns&gt;True if a token was found.&lt;/returns&gt; static bool GetTokenInfo(string value, out string token, out int startIndex, out int endIndex) { token = null; endIndex = -1; startIndex = value.IndexOf("&lt;"); int startTokenEndIndex = value.IndexOf("&gt;"); // No token here if (startIndex &lt; 0) return false; // No token here if (startTokenEndIndex &lt; 0) return false; token = value.Substring(startIndex, startTokenEndIndex - startIndex + 1); // Check for closed token. E.g. &lt;LineBreak/&gt; if (token.EndsWith("/&gt;")) { endIndex = startIndex + token.Length; return true; } string endToken = token.Insert(1, "/"); // Detect nesting; int nesting = 0; int temp_startTokenIndex = -1; int temp_endTokenIndex = -1; int pos = 0; do { temp_startTokenIndex = value.IndexOf(token, pos); temp_endTokenIndex = value.IndexOf(endToken, pos); if (temp_startTokenIndex &gt;= 0 &amp;&amp; temp_startTokenIndex &lt; temp_endTokenIndex) { nesting++; pos = temp_startTokenIndex + token.Length; } else if (temp_endTokenIndex &gt;= 0 &amp;&amp; nesting &gt; 0) { nesting--; pos = temp_endTokenIndex + endToken.Length; } else // Invalid tokenized string return false; } while (nesting &gt; 0); endIndex = pos; return true; } /// &lt;summary&gt; /// Splits the string into sections of tokens and regular text. /// &lt;/summary&gt; /// &lt;param name="value"&gt;The string to split.&lt;/param&gt; /// &lt;returns&gt;An array with the sections.&lt;/returns&gt; static string[] SplitIntoSections(string value) { List&lt;string&gt; sections = new List&lt;string&gt;(); while (!string.IsNullOrEmpty(value)) { string token; int tokenStartIndex, tokenEndIndex; // Check if this is a token section if (GetTokenInfo(value, out token, out tokenStartIndex, out tokenEndIndex)) { // Add pretext if the token isn't from the start if (tokenStartIndex &gt; 0) sections.Add(value.Substring(0, tokenStartIndex)); sections.Add(value.Substring(tokenStartIndex, tokenEndIndex - tokenStartIndex)); value = value.Substring(tokenEndIndex); // Trim away } else { // No tokens, just add the text sections.Add(value); value = null; } } return sections.ToArray(); } private static void FormattedTextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { string value = e.NewValue as string; TextBlock textBlock = sender as TextBlock; if (textBlock != null) textBlock.Inlines.Add(Traverse(value)); } } </code></pre> <hr /> <p><b>Edit:</b> (proposed by Spook)</p> <p>A shorter version, but requires the text to be XML-valid:</p> <pre class="lang-cs prettyprint-override"><code>using System.Xml; // (...) public static class TextBlockHelper { #region FormattedText Attached dependency property 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(TextBlockHelper), new UIPropertyMetadata("", FormattedTextChanged)); private static void FormattedTextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { string value = e.NewValue as string; TextBlock textBlock = sender as TextBlock; if (textBlock != null) { textBlock.Inlines.Clear(); textBlock.Inlines.Add(Process(value)); } } #endregion static Inline Process(string value) { XmlDocument doc = new XmlDocument(); doc.LoadXml(value); Span span = new Span(); InternalProcess(span, doc.ChildNodes[0]); return span; } private static void InternalProcess(Span span, XmlNode xmlNode) { foreach (XmlNode child in xmlNode) { if (child is XmlText) { span.Inlines.Add(new Run(child.InnerText)); } else if (child is XmlElement) { switch (child.Name.ToUpper()) { case "B": case "BOLD": { Span boldSpan = new Span(); InternalProcess(boldSpan, child); Bold bold = new Bold(boldSpan); span.Inlines.Add(bold); break; } case "I": case "ITALIC": { Span italicSpan = new Span(); InternalProcess(italicSpan, child); Italic italic = new Italic(italicSpan); span.Inlines.Add(italic); break; } case "U": case "UNDERLINE": { Span underlineSpan = new Span(); InternalProcess(underlineSpan, child); Underline underline = new Underline(underlineSpan); span.Inlines.Add(underline); break; } } } } } } </code></pre> <p>And an example of usage:</p> <pre><code>&lt;RootItem xmlns:u="clr-namespace:MyApp.Helpers"&gt; &lt;TextBlock u:TextBlockHelper.FormattedText="{Binding SomeProperty}" /&gt; &lt;/RootItem&gt; </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