How To: Create New Character Style
- 2 minutes to read
The following example illustrates how to create a character style in code.
To achieve the required result, do the following:
- Create a new style using the CharacterStyleCollection.CreateNew method;
- Specify the style settings with the use of corresponding CharacterStyle object properties;
- Add the style to the collection of character styles, represented by the CharacterStyleCollection object. To do that, use the CharacterStyleCollection.Add method. The collection is accessible through the Document.CharacterStyles property.
The following code snippet creates a new character style via the CharacterStyleCollection.CreateNew method, specifies style settings, adds it to the document style collection and applies the style to the specified range.
Note
A complete sample project is available at https://github.com/DevExpress-Examples/winforms-richedit-document-api-e5219
document.LoadDocument("Grimm.docx", DevExpress.XtraRichEdit.DocumentFormat.OpenXml);
CharacterStyle cstyle = document.CharacterStyles["MyCStyle"];
if (cstyle == null)
{
cstyle = document.CharacterStyles.CreateNew();
cstyle.Name = "MyCStyle";
cstyle.Parent = document.CharacterStyles["Default Paragraph Font"];
cstyle.ForeColor = System.Drawing.Color.DarkOrange;
cstyle.Strikeout = StrikeoutType.Double;
cstyle.FontName = "Verdana";
document.CharacterStyles.Add(cstyle);
}
DocumentRange myRange = document.Paragraphs[0].Range;
CharacterProperties charProps =
document.BeginUpdateCharacters(myRange);
charProps.Style = cstyle;
document.EndUpdateCharacters(charProps);