Skip to main content
All docs
V19.1

How to: Insert a Field to a Document

  • 2 minutes to read

The following example illustrates how to add and modify fields manually.

All the fields in the document are contained in the FieldCollection, accessible through the SubDocument.Fields property.

Insert a Field

To create a field, use the FieldCollection.Create property, as illustrated below.

Note

A complete sample project is available at https://github.com/DevExpress-Examples/wpf-richedit-document-api-t213968.

document.BeginUpdate();
document.Fields.Create(document.CaretPosition, "DATE");
document.Fields.Update();
document.EndUpdate();

To create a field from the selected range, use the FieldCollection.Create property with the passed range.

Note

A complete sample project is available at https://github.com/DevExpress-Examples/wpf-richedit-document-api-t213968.

document.BeginUpdate();
document.AppendText("SYMBOL 0x54 \\f Wingdings \\s 24");
document.EndUpdate();
document.Fields.Create(document.Paragraphs[0].Range);
document.Fields.Update();

Modify Field Code

To modify field content, use the SubDocument.BeginUpdate - SubDocument.EndUpdate paired methods.

To insert a field format switch, use the SubDocument.InsertText method. Use the end position of the field code range as a method argument.

Use the Field.Update method to update the field result.

Note

A complete sample project is available at https://github.com/DevExpress-Examples/wpf-richedit-document-api-t213968.

DocumentPosition caretPosition = document.CaretPosition;
SubDocument currentDocument = caretPosition.BeginUpdateDocument();

//Create a DATE field at the caret position
currentDocument.Fields.Create(caretPosition, "DATE");
currentDocument.EndUpdate();

for (int i = 0; i < currentDocument.Fields.Count; i++)
{
    string fieldCode = document.GetText(currentDocument.Fields[i].CodeRange);
    if (fieldCode == "DATE")
    {
        //Retrieve the range obtained by the field code
        DocumentPosition position = currentDocument.Fields[i].CodeRange.End;

        //Insert the format switch to the end of the field code range
        currentDocument.InsertText(position, @"\@ ""M/d/yyyy h:mm am/pm""");
    }
}

//Update all document fields
currentDocument.Fields.Update();
See Also