This is a migrated thread and some comments may be shown as answers.

Insert Merge Field with Formatting programatically

1 Answer 369 Views
RichTextBox
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
colin
Top achievements
Rank 1
colin asked on 19 Jun 2012, 10:16 AM
I want to insert a merge field programatically into my RadDocument.
When I insert the field I want it to have a specific style (font, size) and ignore the current style for the current position of the document.

I can insert the field user the Insertfield() function on a RadDocument but how can I then change the style for that merge field afterwards?

1 Answer, 1 is accepted

Sort by
0
Iva Toteva
Telerik team
answered on 22 Jun 2012, 11:00 AM
Hi Colin,

You can insert a merge field with specific formatting in the following way:

RadDocument document = new RadDocument();
Section section = new Section();
Paragraph paragraph = new Paragraph();
 
FieldRangeStart start = new FieldRangeStart();
FieldRangeEnd end = new FieldRangeEnd();
end.Start = start;
start.Field = new MergeField() { PropertyPath = "FirstName" };
Span span = new Span("{MERGEFIELD FirstName}");
span.FontSize = Unit.PointToDip(18);
span.ForeColor = Colors.Green;
 
paragraph.Inlines.Add(start);
paragraph.Inlines.Add(span);
paragraph.Inlines.Add(end);
 
section.Blocks.Add(paragraph);
document.Sections.Add(section);
 
document.MeasureAndArrangeInDefaultSize();
document.Selection.SelectAll();
DocumentFragment fragment = document.Selection.CopySelectedDocumentElements();
 
this.editor.InsertFragment(fragment);

The other option would be to change the formatting of the merge field after you have inserted it. However, in this way the actions will be registered separately in the history stack and will be undone one by one:
this.editor.InsertField(new MergeField() { PropertyPath = "FirstName" });
DocumentPosition position = new DocumentPosition(this.editor.Document.CaretPosition);
position.MoveToPrevious();
FieldRangeEnd fieldEnd = position.GetCurrentInline() as FieldRangeEnd;
if (fieldEnd != null)
{
    FieldRangeStart start = (FieldRangeStart)fieldEnd.Start;
    this.editor.Document.Selection.SelectAnnotationRange(start);
 
    this.editor.ChangeFontSize(Unit.PointToDip(18));
    this.editor.ChangeTextForeColor(Colors.Green);
    this.editor.Document.Selection.Clear();
}

I hope this answers your question.

Greetings,
Iva Toteva
the Telerik team

Explore the entire Telerik portfolio by downloading the Ultimate Collection trial package. Get it now >>

Tags
RichTextBox
Asked by
colin
Top achievements
Rank 1
Answers by
Iva Toteva
Telerik team
Share this question
or