About WPF RichTextBox

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.


//TextBox
int lastPosition = tbxConsole.Text.Length;
tbxConsole.Focus();
tbxConsole.SelectionStart = lastPosition;
tbxConsole.SelectionLength = 0;

vs.

//RichTextBox
tbxConsole.CaretPosition = tbxConsole.CaretPosition.DocumentEnd;

Assigning text is slightly trickier. You use TextRage.

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.

<RichTextBox Name="tbxConsole" AcceptsTab="False" AcceptsReturn="False" Background="Black" Foreground="#FF28C128" HorizontalAlignment="Left"
		 PreviewKeyDown="TbxConsolePreviewKeyDown">
	<RichTextBox.Resources>
		<Style TargetType="{x:Type Paragraph}">
			<Setter Property="Margin" Value="0" />
		</Style>
	</RichTextBox.Resources>
</RichTextBox>

to be contined …

About WPF RichTextBox