Udostępnij za pośrednictwem


RichEditBox, Store apps and the challenges with advanced text formatting

This has become a common topic people ask me about so I decided to write it down for future reference.

 

If you are using RichEditBox on a store app, you might have realized by now that coding specific format changes in parts of the content is not trivial. Different than RichTextBlock which has a very extensible, c# friendly way of defining paragraphs and custom formatting inside of it (but is not an user editable control), RichTextBlock will allow you to reach some basic properties in order to format the entire content as a single unit, but no c# specific classes and methods for, let's say, format a specific subset of the content with a different font color.

So how do you do that if you need to?

 

I typically suggest two options:

 

1-Rely on RTF:

RichEditBox understands RTF well. So you can either load an entirely RTF formatted document or update parts of a content with RTF tags. For example, imagine the user selects part of the text and you want to format that part only with a different font color. You can do that in a relatively simple way doing this:

 

 string text;
richText1.Document.Selection.GetText(Windows.UI.Text.TextGetOptions.None, out text);
richText1.Document.Selection.SetText(Windows.UI.Text.TextSetOptions.FormatRtf, 
                   "{\\rtf1\\ansi\\deff0" +
                   "{\\colortbl;\\red0\\green0\\blue0;\\red255\\green255\\blue0;}" +
                   "\\cf2" + text + "}");

What we are doing here is getting the selected text on screen, keeping it in a variable, then overwriting it with a RTF content that enforces a specific color definition. In other words, for anything the RichEditBox can't do with it's properties and methods, RTF can.

 I have published this sample here.

2-Use a HTML based rich text editor.

 

Another approach to this problem is to just use a WebView control and load it with a HTML/JS based rich text editor. That way you now have control over the entire HTML content, which will let you do as much as HTML can. There are many sample rich text editors in HTML you can rely on for this.

Comments

  • Anonymous
    December 25, 2014
    You code works very well.. but when looking for more, such Bold or Italic, I found this way: Windows.UI.Text.ITextCharacterFormat format = richText1.Document.Selection.CharacterFormat; format.ForegroundColor = Windows.UI.Color.FromArgb(0, 255, 255, 0); I test in both, Windows and Phone

  • Anonymous
    December 25, 2014
    Also this way works: richEdit1.Document.Selection.CharacterFormat.ForegroundColor = Colors.Yellow;

  • Anonymous
    December 25, 2014
    Good points, SuNcO. For some things you don't need to dive into RTF.

  • Anonymous
    April 27, 2016
    Can you suggest how to add HTML rich text editor with WebView control?