The RichTextBox control in Windows Presentation Foundation (WPF) is a powerful UI component that allows users to input, display, and edit rich formatted text. Unlike the simpler TextBox, the RichTextBox supports features like bold, italic, colored text, bullet points, hyperlinks, images, and more — all encapsulated in a FlowDocument
.
In this post, we'll cover:
- Creating RichTextBox
- Reading and Writing Text
- Formating RichTextBox Text
- Saving RichTextBox Content
Working With RichTextBox in WPF
Getting Started
The RichTextBox
in WPF is based on the FlowDocument
model. This model allows for flexible and complex content, enabling developers to structure content with paragraphs, images, and interactive elements.
Key Features Of RichTextBox in WPF
- Rich text formatting (bold, italic, underline, etc.)
- Support for
RTF
,XAML
, andPlain Text
formats - Embedding images and other UI elements
- Undo/redo functionality
- Full control over text selection, caret, and editing behavior
This WPF RichTextBox demonstration is conducted in Visual Studio 2022 using .NET Framework 4.8. It will work with .NET Framework 4.8 and later versions.
Working With RichTextBox in WPF
Creating RichTextBox
The code below shows how to create a RichTextBox that a user can edit rich content in.
Creating RichTextBox in WPF XAML
<Window x:Class="WPFRichtextbox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="23"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Text="Richtextbox demonstration" Margin="10,5"/>
<RichTextBox Grid.Row="1" Name="richTextBox" Margin="10,0,10,10" />
</Grid>
</Window>
You can add a RichTextBox
to the WPF Window as a child of Grid
like the XAMPL code through code behind(C#) also, Below are the C# code examples:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.AddRichtextbox();
}
void AddRichtextbox()
{
RichTextBox richTextBox = new RichTextBox();
richTextBox.Margin=new Thickness(10,0,10,10);
this.gdgrid.Children.Add(richTextBox);
Grid.SetRow(richTextBox, 1);
}
}
Interacting With RichTextBox in WPF
Specifically, the content edited in a RichTextBox is flow content. To contain flow content, a RichTextBox hosts a FlowDocument object, which in turn contains the editable content. The following code demonstrates how to create a RichTextBox with a paragraph using both XAML and C#, and how to insert an image and a hyperlink programmatically.
Adding RichTextBox Text(WPF XAML) <RichTextBox Grid.Row="1" Name="richTextBox" Margin="10,0,10,10" GotMouseCapture="Selection_Changed" >
<FlowDocument>
<Paragraph>
This is a demonstration of RichTextBox in WPF.
</Paragraph>
</FlowDocument>
</RichTextBox>
Adding RichTextBox Text(C# Code)
RichTextBox richTextBox = new RichTextBox();
richTextBox.Document.Blocks.Clear();
richTextBox.Document.Blocks.Add(new Paragraph(new Run("This is a demonstration of RichTextBox in WPF.")));
Inserting Elements
Inserting Image
Image image = new Image();
image.Source = new BitmapImage(new Uri("your_image_path.jpg", UriKind.RelativeOrAbsolute));
image.Width = 100;
InlineUIContainer container = new InlineUIContainer(image);
Paragraph paragraph = new Paragraph(container);
richTextBox.Document.Blocks.Add(paragraph);
Insert Hyperlink
Paragraph paragraph = new Paragraph();
Hyperlink link = new Hyperlink(new Run("Kailash's Blogs")) {
NavigateUri = new Uri("https://www.kailashsblogs.com")
};
link.RequestNavigate += (s, e) => Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri) { UseShellExecute = true });
paragraph.Inlines.Add(link);
richTextBox.Document.Blocks.Add(paragraph);
Formatting RichTextBox in WPF
Formatting a RichTextBox in WPF (Windows Presentation Foundation) involves interacting with its FlowDocument content. This allows you to apply formatting such as font styles, colors, alignment, bullets, images, and hyperlinks. Below is a comprehensive example of formatting a RichTextBox using XAML and C#.
Formatting RichTextBox Text(WPF XAML) <RichTextBox Grid.Row="1" Name="richTextBox" Margin="10,0,10,10" GotMouseCapture="Selection_Changed" >
<FlowDocument>
<Paragraph FontStyle="Italic" FontWeight="Bold" FontSize="14" FontFamily="Arial">
This is a demonstration of RichTextBox in WPF.
</Paragraph>
</FlowDocument>
</RichTextBox>
Formatting Text Programmatically
Formatting text programmatically in a WPF RichTextBox is commonly done using the Selection property and the ApplyPropertyValue method. This allows you to change properties like font size, color, bold, italic, underline, etc., for the currently selected text or a specific TextRange.
Bold, Italic, Underline
// Make selected text bold
richTextBox.Selection.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
// Italic
richTextBox.Selection.ApplyPropertyValue(TextElement.FontStyleProperty, FontStyles.Italic);
// Underline (Wrap in an Underline element)
TextRange selectionRange = new TextRange(richTextBox.Selection.Start, richTextBox.Selection.End);
if (!selectionRange.IsEmpty)
{
selectionRange.ApplyPropertyValue(Inline.TextDecorationsProperty, TextDecorations.Underline);
}
Change Font Size and Font Family
// Set font size
richTextBox.Selection.ApplyPropertyValue(TextElement.FontSizeProperty, 20.0);
// Set font family
richTextBox.Selection.ApplyPropertyValue(TextElement.FontFamilyProperty, new FontFamily("Consolas"));
Change Font Color
// Set foreground (text) color
richTextBox.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);
// Set background (highlight) color
richTextBox.Selection.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.LightYellow);
Apply Alignment to Paragraphs
Paragraph paragraph = richTextBox.Selection.Start.Paragraph;
if (paragraph != null)
{
paragraph.TextAlignment = TextAlignment.Center;
}
Apply Formatting Without Selecting Text
TextPointer start = richTextBox.Document.ContentStart.GetPositionAtOffset(10);
TextPointer end = richTextBox.Document.ContentStart.GetPositionAtOffset(30);
if (start != null && end != null)
{
TextRange range = new TextRange(start, end);
range.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
}
Loading and Saving Rich Text (RTF/Plain Text)
You can load and save content in different formats like RTF and plain text.
Save to File
private void Save()
{
using (FileStream fs = File.Create("output.rtf"))
{
TextRange range = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
range.Save(fs, DataFormats.Rtf);
}
}
Load from File
private void Load()
{
using (FileStream fs = File.OpenRead("output.rtf"))
{
TextRange range = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
range.Load(fs, DataFormats.Rtf);
}
}
You can replace DataFormats.Rtf with DataFormats.Text or DataFormats.Xaml depending on your need.
Summary
The WPF RichTextBox
is more than just a multi-line text editor; it’s a mini rich text editor embedded in your app. With support for FlowDocument
, programmatic formatting, and user interaction, it's ideal for applications like email clients, document editors, and notes apps.
Whether you're saving documents or building an editor, the key is mastering how to manipulate the underlying FlowDocument and its components. I hope this was helpful to you
Thanks