Back to Devexpress

How to: Change Formatting of Selected Text

wpf-10059-controls-and-libraries-rich-text-editor-examples-formatting-how-to-change-formatting-of-selected-text.md

latest3.1 KB
Original Source

How to: Change Formatting of Selected Text

  • Oct 02, 2023

This example demonstrates how you can get the selected text in code, and modify character format attributes, such as CharacterPropertiesBase.FontName, CharacterPropertiesBase.FontSize, CharacterPropertiesBase.ForeColor, CharacterPropertiesBase.BackColor, etc.

Use the Document.Selection property to obtain the DocumentRange object specifying an end-user selection. Then, call the SubDocument.BeginUpdateCharacters method for the specified range, modify the properties of the returned CharacterProperties object, and call the SubDocument.EndUpdateCharacters method to finalize the modification.

Note

Make sure that the SubDocument.BeginUpdateCharacters method always has its corresponding SubDocument.EndUpdateCharacters method to ensure proper operation of the control.

The result is shown below:

csharp
using System.Windows;
using System.Drawing;
using DevExpress.XtraRichEdit;
using DevExpress.Office.Utils;
using DevExpress.XtraRichEdit.API.Native;

Document doc = richEditControl1.Document;
DocumentRange range = doc.Selection;
CharacterProperties cp = doc.BeginUpdateCharacters(range);
cp.FontName = "Comic Sans MS";
cp.FontSize = 18;
cp.ForeColor = Color.Yellow;
cp.BackColor = Color.Blue;
cp.Underline = UnderlineType.DoubleWave;
cp.UnderlineColor = Color.White;
doc.EndUpdateCharacters(cp);
vb
Imports System.Windows
Imports System.Drawing
Imports DevExpress.XtraRichEdit
Imports DevExpress.Office.Utils
Imports DevExpress.XtraRichEdit.API.Native

Dim doc As Document = richEditControl1.Document
Dim range As DocumentRange = doc.Selection
Dim cp As CharacterProperties = doc.BeginUpdateCharacters(range)
cp.FontName = "Comic Sans MS"
cp.FontSize = 18
cp.ForeColor = Color.Yellow
cp.BackColor = Color.Blue
cp.Underline = UnderlineType.DoubleWave
cp.UnderlineColor = Color.White
doc.EndUpdateCharacters(cp)