RichTextBox Tips

Although this blog is about XAML only I decided to take on the next step and write some code behind.

1. How to get selection range excluding the UIElements and such from RichTextBox:

            StartIndex = new TextRange(richTextBox.Document.ContentStart, richTextBox.Selection.Start).Text.Length;
            Count = new TextRange(richTextBox.Document.ContentStart, richTextBox.Selection.End).Text.Length - StartIndex;

2. How to change font weight, change to italic, etc of selected text:

            EditingCommands.ToggleBold.Execute(null, richTextBox);

3. How to change background color or other attributes of selected text:

            Span span = new Span(richTextBox.Selection.Start, richTextBox.Selection.End);
            span.Background = Brushes.Red;
Note that the span you create will update only the part of the text that does not overlap with another span or element

For example: text<Span> sample</Span>

If you try adding a span for "text sa" then only the "text" part will be updated since the " sa" text is inside another element.