public static FlowDocument ColorizeXAML(string xamlText, FlowDocument targetDoc) { XmlTokenizer tokenizer = new XmlTokenizer(); XmlTokenizerMode mode = XmlTokenizerMode.OutsideElement; List <XmlToken> tokens = tokenizer.Tokenize(xamlText, ref mode); List <string> tokenTexts = new List <string>(tokens.Count); List <Color> colors = new List <Color>(tokens.Count); int position = 0; foreach (XmlToken token in tokens) { string tokenText = xamlText.Substring(position, token.Length); tokenTexts.Add(tokenText); Color color = ColorForToken(token, tokenText); colors.Add(color); position += token.Length; } Paragraph p = new Paragraph(); // Loop through tokens for (int i = 0; i < tokenTexts.Count; i++) { Run r = new Run(tokenTexts[i]); r.Foreground = new SolidColorBrush(colors[i]); p.Inlines.Add(r); } targetDoc.Blocks.Add(p); return(targetDoc); }
/// <summary> /// Format Xml in the passed rich text box. /// </summary> /// <param name="xmlEditor"></param> public static void FormatXml(RichTextBox xmlEditor) { // Stop redrawing RichTextDrawing.StopRedraw(xmlEditor); // Tokenize the Xml string List <XmlToken> tokens = XmlTokenizer.Tokenize(xmlEditor.Text); foreach (XmlToken token in tokens) { xmlEditor.Select(token.Index, token.Text.Length); switch (token.Type) { case XmlTokenType.None: xmlEditor.SelectionColor = xmlEditor.ForeColor; break; case XmlTokenType.SpecialChar: xmlEditor.SelectionColor = specialCharColor; break; case XmlTokenType.Escape: xmlEditor.SelectionColor = escapeColor; break; case XmlTokenType.Element: xmlEditor.SelectionColor = elementColor; break; case XmlTokenType.Attribute: xmlEditor.SelectionColor = attributeColor; break; case XmlTokenType.Value: xmlEditor.SelectionColor = valueColor; break; case XmlTokenType.Comment: xmlEditor.SelectionColor = commentColor; break; } } // Sample code to show that the perf problem is a RichTexBox problem //string content = xmlEditor.Text; //Random gen = new Random(); //for (int i = 0; i < content.Length; i++) //{ // xmlEditor.Select(i, 1); // Color c = Color.FromArgb(gen.Next(256), gen.Next(256), gen.Next(256)); // xmlEditor.SelectionColor = c; //} // Resume redraw RichTextDrawing.RestoreRedraw(xmlEditor); }