About WPF RichTextBox

less than 1 minute read

This content is moved from Console+ post, as I use Avalon Text Editor, not RichTextBox, for the project.

It's an interesting control. Because now I can read the shell's screen buffer and write it into textbox, I wanted to use RichTextBox, to change the colors of some texts. It behaves very similar to textbox and the internal seems to be quite different. Maybe it's a victory of OOP, that TextBox and RichTextBox share large part of the interface, even thought the internals are so different.

Moving cursor or caret is easier with RichTextBox.

[sourcecode language="csharp"]

int lastPosition = tbxConsole.Text.Length;
tbxConsole.SelectionStart = lastPosition;
tbxConsole.SelectionLength = 0;


tbxConsole.CaretPosition = tbxConsole.CaretPosition.DocumentEnd;


Assigning text is slightly trickier. You use TextRage.

[sourcecode language="csharp"]
new TextRange(tbxConsole.Document.ContentStart, tbxConsole.Document.ContentEnd)
Text = _console.ReadAll()


Nobody seems to like the empty line RichTextBox inserts between paragraph. I am not happy either, so set the height of the paragraph to zero, thanks to a guy with style.

[sourcecode language="xml"]
<RichTextBox Name="tbxConsole" AcceptsTab="False" AcceptsReturn="False" Background="Black" Foreground="#FF28C128" HorizontalAlignment="Left"
<Style TargetType="{x:Type Paragraph}">
<Setter Property="Margin" Value="0" />

to be contined ...