Skip to main content

RichEditControl.CalculateDocumentVariable Event

Fires when the DOCVARIABLE field is updated.

Namespace: DevExpress.Xpf.RichEdit

Assembly: DevExpress.Xpf.RichEdit.v24.1.dll

NuGet Package: DevExpress.Wpf.RichEdit

Declaration

public event CalculateDocumentVariableEventHandler CalculateDocumentVariable

Event Data

The CalculateDocumentVariable event's data class is CalculateDocumentVariableEventArgs. The following properties provide information specific to this event:

Property Description
Arguments Provides access to a collection of arguments within the DOCVARIABLE field.
FieldLocked Gets or sets a locked attribute to the field for which the event occurs.
Handled Gets or sets whether the default action is required.
KeepLastParagraph Gets or sets whether the last paragraph of the inserted document is kept in the resulting document.
PreserveInsertedContentFormatting Gets or sets whether to insert an additional hidden paragraph so that the inserted content is not formatted with the DOCVARIABLE field’s paragraph formatting.
Value Gets or sets the value of the DOCVARIABLE field that fired the event.
VariableName Gets the name of the document variable to which the DOCVARIABLE field refers.

Remarks

The CalculateDocumentVariable event fires when one of the following operations with a DOCVARIABLE field occurs:

Handle this event to analyze DOCVARIABLE field switches and arguments, and specify custom content to insert into this field.

Assign a DocVariableValue.Current value to the CalculateDocumentVariableEventArgs.Value property and set e.Handled to true to retain the existing DOCVARIABLE value.

Locked DOCVARIABLE Fields

You can specify the DXRichEditFieldOptions.UpdateLockedFields property to raise the event for locked DOCVARIABLE fields.

Use the CalculateDocumentVariableEventArgs.FieldLocked property to lock/unlock the field in the CalculateDocumentVariable handler. Set e.Handled to true to apply changes.

Nested DOCVARIABLE Fields

If you use the RichEditControl.MailMerge method to evaluate nested DOCVARIABLE fields, set the DXRichEditMailMergeOptions.ViewMergedData option to true. Otherwise, you get field placeholders instead of values in the CalculateDocumentVariable handler.

Check the field’s CalculateDocumentVariableEventArgs.Arguments value to retrieve a nested field value. When the CalculateDocumentVariable event is fired for the first time, e.Arguments contains the <<FieldName_1>> (the placeholder for the field), because the merge field has not yet been calculated. In this case, do nothing in the event handler (use comparison and return statements if required).

Note

If you use the MailMerge method overload with a document parameter, handle the CalculateDocumentVariable event of a SubDocument passed as a parameter instead of the RichEditControl.CalculateDocumentVariable event.

Examples

How to: Handle the CalculateDocumentVariable Event to Insert Formatted String

This code snippet demonstrates how to handle the RichEditControl.CalculateDocumentVariable event to insert dynamic content into the document. In this example, it is used to get weather report or geo coordinates from Google web service. A variable name specified in the DOCVARIABLE field indicates a choice between location and weather, while the location itself is specified by the field argument.

View Example

void eventHandler_CalculateDocumentVariable(object sender, CalculateDocumentVariableEventArgs e) {
    string location = e.Arguments[0].Value.ToString();

    Console.WriteLine(e.VariableName + " " + location);

    if ((location.Trim() == String.Empty) || (location.Contains("<"))) {
        e.Value = " ";
        e.Handled = true;
        return;
    }

    switch (e.VariableName) {
        //case "Weather":
        //    Conditions conditions = new Conditions();
        //    conditions = Weather.GetCurrentConditions(location);
        //    e.Value = String.Format("Forecast for {0}: \nConditions: {1}\nTemperature (C) :{2}\nHumidity: {3}\nWind: {4}\n",
        //        conditions.City, conditions.Condition, conditions.TempC, conditions.Humidity, conditions.Wind);
        //    break;
        case "Location":
            GeoLocation[] loc = GeoLocation.GeocodeAddress(location);
            e.Value = String.Format(" {0}\nLatitude: {1}\nLongitude: {2}\n",
                loc[0].Address, loc[0].Latitude.ToString(), loc[0].Longitude.ToString());
            break;
    }
    e.Handled = true;
}

How to: Handle the Event to Insert a Document Element

The code sample below shows how to handle the RichEditControl.CalculateDocumentVariable event to insert a barcode and a table:

result

using DevExpress.BarCodes;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraRichEdit;
using DevExpress.XtraRichEdit.API.Native;
using System.Drawing;
using System.Text;
//...

richEditControl.CreateNewDocument();
Document document = richEditControl.Document;

// Create fields for a barcode and a table:
document.Fields.Create(document.Range.End, "DOCVARIABLE QRCODE");
document.Paragraphs.Append();
document.Fields.Create(document.Range.End, "DOCVARIABLE TABLE");

richEditControl.CalculateDocumentVariable += RichEditControl_CalculateDocumentVariable;
richEditControl.BeforeExport += RichEditControl_BeforeExport;

// Update all document fields:
document.UpdateAllFields();

// Save the result:
richEditControl.SaveDocument("result.docx", DocumentFormat.OpenXml);

private void RichEditControl_BeforeExport(object sender, BeforeExportEventArgs e)
{
    richEditControl.Document.UnlinkAllFields();
}

void RichEditControl_CalculateDocumentVariable(object sender, CalculateDocumentVariableEventArgs e)
{
    switch (e.VariableName)
    {
        case "QRCODE":
            // Create new RichEditDocumentServer instance:
            var doc = new RichEditDocumentServer();

            // Insert a barcode as a shape
            Shape picture = doc.Document.Shapes.InsertPicture(doc.Document.Range.End, GenerateQrCode());
            picture.TextWrapping = TextWrappingType.InLineWithText;

            // Set the field value to the RichEditDocumentServer instance:
            e.Value = doc;
            e.Handled = true;
            break;
        case "TABLE":
            // Create new RichEditDocumentServer instance:
            var doc1 = new RichEditDocumentServer();

            // Insert a table:
            GenerateTable(doc1.Document);

            // Set the field value to the RichEditDocumentServer instance:
            e.Value = doc1;
            e.Handled = true;
            break;
    }
}

// This method generates a barcode:
Bitmap GenerateQrCode()
{
    BarCode barCode = new BarCode();
    barCode.Symbology = Symbology.QRCode;
    barCode.CodeText = "https://www.devexpress.com/";
    barCode.BackColor = Color.White;
    barCode.ForeColor = Color.Black;
    barCode.RotationAngle = 0;
    barCode.CodeBinaryData = Encoding.Default.GetBytes(barCode.CodeText);
    barCode.Options.QRCode.CompactionMode = QRCodeCompactionMode.Byte;
    barCode.Options.QRCode.ErrorLevel = QRCodeErrorLevel.Q;
    barCode.Options.QRCode.ShowCodeText = false;
    barCode.DpiX = 72;
    barCode.DpiY = 72;
    barCode.Module = 2f;

    return barCode.BarCodeImage;
}

// This method generates a table:
Table GenerateTable(Document document)
{
    Table table = document.Tables.Create(document.Range.Start, 3, 3);

    document.InsertSingleLineText(table.Rows[0].Cells[1].Range.Start, "Active Customers");
    document.InsertSingleLineText(table[1, 0].Range.Start, "Photo");
    document.InsertSingleLineText(table[1, 1].Range.Start, "Customer Info");
    document.InsertSingleLineText(table[1, 2].Range.Start, "Rentals");

    return table;
}

The following code snippet (auto-collected from DevExpress Examples) contains a reference to the CalculateDocumentVariable event.

Note

The algorithm used to collect these code examples remains a work in progress. Accordingly, the links and snippets below may produce inaccurate results. If you encounter an issue with code examples below, please use the feedback form on this page to report the issue.

See Also