How to Append Colored Text to WPF RichTextBox Using AppendText Function
The WPF RichTextBox is a powerful control for displaying and editing formatted text, supporting features like different fonts, colors, and hyperlinks. While its built-in AppendText method is convenient for adding plain text, it lacks direct support for styling (e.g., color). This blog will guide you through appending colored text to a RichTextBox by working around AppendText limitations, using WPF’s document model (e.g., FlowDocument, Paragraph, Run). By the end, you’ll be able to dynamically add styled text to your RichTextBox with ease.
Table of Contents#
- Prerequisites
- Understanding
RichTextBoxandAppendTextLimitations - Step-by-Step Guide to Append Colored Text
- Advanced Scenarios
- Troubleshooting Common Issues
- Conclusion
- References
Prerequisites#
To follow along, ensure you have:
- Visual Studio (2019 or later) with the .NET Desktop Development workload installed.
- Basic knowledge of C# and XAML.
- Familiarity with WPF controls (e.g.,
Button,RichTextBox).
Understanding RichTextBox and AppendText Limitations#
The RichTextBox in WPF uses a FlowDocument as its content model. A FlowDocument consists of Block elements (e.g., Paragraph), which contain Inline elements (e.g., Run, Hyperlink). The Run element is used for plain text and supports styling (color, font, etc.).
The built-in AppendText(string text) method simplifies adding text but only appends plain, unstyled text to the RichTextBox. It does not support color, font changes, or other formatting. To add colored text, we must directly manipulate the FlowDocument by creating styled Run elements and inserting them into the document.
Step-by-Step Guide to Append Colored Text#
3.1 Set Up the WPF Project#
- Open Visual Studio.
- Create a new WPF App (.NET Framework) or WPF App (.NET) project (e.g., "ColoredRichTextBoxDemo").
3.2 Add RichTextBox to XAML#
Open MainWindow.xaml and replace the default Grid with the following XAML. This adds a RichTextBox (to display text) and a Button (to trigger text insertion):
<Window x:Class="ColoredRichTextBoxDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Colored RichTextBox Demo" Height="450" Width="800">
<Grid Margin="10">
<!-- RichTextBox to display colored text -->
<RichTextBox x:Name="rtbLog" Margin="0,0,0,50"
VerticalScrollBarVisibility="Auto"/>
<!-- Button to trigger text insertion -->
<Button Content="Append Colored Text"
HorizontalAlignment="Center"
VerticalAlignment="Bottom"
Click="AppendTextButton_Click"
Width="150" Height="30"/>
</Grid>
</Window>x:Name="rtbLog": Gives theRichTextBoxa name to access it in code-behind.VerticalScrollBarVisibility="Auto": Adds a scrollbar when text overflows.
3.3 Create a Method to Append Colored Text#
In MainWindow.xaml.cs, add a method to append styled text to the RichTextBox. This method will:
- Get the
RichTextBox’sFlowDocument. - Retrieve or create a
Paragraph(to hold the text). - Create a
Runelement with the text and desired color. - Add the
Runto theParagraph.
Here’s the code:
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
namespace ColoredRichTextBoxDemo
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
// Method to append colored text to RichTextBox
private void AppendColoredText(string text, Brush textColor)
{
// Get the current document (FlowDocument) of the RichTextBox
FlowDocument doc = rtbLog.Document;
// Get the current paragraph (or create one if none exists)
Paragraph paragraph = doc.Blocks.LastBlock as Paragraph;
if (paragraph == null)
{
paragraph = new Paragraph();
doc.Blocks.Add(paragraph); // Add new paragraph to the document
}
// Create a Run element with the text and color
Run run = new Run(text)
{
Foreground = textColor // Set text color
};
// Add the Run to the paragraph
paragraph.Inlines.Add(run);
// Optional: Scroll to the end to show new text
rtbLog.ScrollToEnd();
}
// Button click event to test the method
private void AppendTextButton_Click(object sender, RoutedEventArgs e)
{
// Append red text
AppendColoredText("This is red text!\n", Brushes.Red);
// Append blue text
AppendColoredText("This is blue text!\n", Brushes.Blue);
// Append green text with custom RGB color
Brush customGreen = new SolidColorBrush(Color.FromRgb(0, 200, 0));
AppendColoredText("This is custom green text!\n", customGreen);
}
}
}3.4 Test the Implementation#
Run the project (F5). Click the "Append Colored Text" button. You’ll see:
- Red text: "This is red text!"
- Blue text: "This is blue text!"
- Custom green text: "This is custom green text!"
The RichTextBox will display all three lines with their respective colors.
Advanced Scenarios#
4.1 Custom Fonts, Sizes, and Styles#
Extend the AppendColoredText method to support fonts, sizes, and styles (bold/italic) by modifying the Run properties:
private void AppendStyledText(string text, Brush color, double fontSize = 12,
FontWeight weight = FontWeights.Normal,
FontStyle style = FontStyles.Normal)
{
Paragraph paragraph = rtbLog.Document.Blocks.LastBlock as Paragraph ?? new Paragraph();
if (paragraph == null)
{
paragraph = new Paragraph();
rtbLog.Document.Blocks.Add(paragraph);
}
Run run = new Run(text)
{
Foreground = color,
FontSize = fontSize,
FontWeight = weight,
FontStyle = style
};
paragraph.Inlines.Add(run);
rtbLog.ScrollToEnd();
}
// Usage: Append bold, 14pt, italic red text
AppendStyledText("Bold, italic, 14pt red text!\n", Brushes.Red, 14, FontWeights.Bold, FontStyles.Italic);4.2 Background Colors#
To add a background color to text, set the Background property of the Run:
Run run = new Run("Text with yellow background!")
{
Foreground = Brushes.Black,
Background = Brushes.Yellow // Set background color
};4.3 Hyperlinks#
Add clickable hyperlinks using the Hyperlink element (instead of Run):
private void AppendHyperlink(string text, Uri uri)
{
Paragraph paragraph = rtbLog.Document.Blocks.LastBlock as Paragraph ?? new Paragraph();
if (paragraph == null)
{
paragraph = new Paragraph();
rtbLog.Document.Blocks.Add(paragraph);
}
Hyperlink link = new Hyperlink(new Run(text))
{
NavigateUri = uri,
Foreground = Brushes.Blue,
TextDecorations = TextDecorations.Underline
};
// Handle link clicks (requires using System.Diagnostics)
link.RequestNavigate += (s, e) =>
{
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri) { UseShellExecute = true });
e.Handled = true;
};
paragraph.Inlines.Add(link);
paragraph.Inlines.Add(new Run("\n")); // Add newline after link
}
// Usage: Append a link to Microsoft's docs
AppendHyperlink("Visit WPF Docs", new Uri("https://learn.microsoft.com/en-us/dotnet/desktop/wpf/"));Troubleshooting Common Issues#
Text Not Appearing?#
- Ensure the
Runis added to theParagraph(viaparagraph.Inlines.Add(run)). - If the
RichTextBoxis empty, the initialdoc.Blocks.LastBlockwill benull—the code handles this by creating a newParagraph.
Color Not Showing?#
- Use
System.Windows.Media.Brush(e.g.,Brushes.Red) instead ofSystem.Drawing.Color(from Windows Forms). - For custom colors, use
SolidColorBrushwithColor.FromRgb(red, green, blue)(values 0–255).
Performance with Large Text?#
For apps appending thousands of lines (e.g., logs), use rtbLog.BeginChange() and rtbLog.EndChange() to batch updates and reduce flickering:
using (rtbLog.Document.Blocks.DeferRefresh()) // Alternative to Begin/EndChange
{
AppendColoredText("Batch update line 1\n", Brushes.Gray);
AppendColoredText("Batch update line 2\n", Brushes.Gray);
}Conclusion#
While RichTextBox.AppendText is limited to plain text, you can append colored/styled text by manipulating the FlowDocument directly. By creating Run elements with custom Foreground brushes and inserting them into Paragraph blocks, you gain full control over text formatting. Extend this approach to support fonts, hyperlinks, and backgrounds for rich, dynamic UIs.