/// <summary> /// Inserts the text to rich text box at position. /// </summary> /// <param name="richTextBox">The rich text box.</param> /// <param name="text">The text.</param> public void InsertTextToRichTextBoxAtPosition(RichTextBox richTextBox, string text) { StringToFlowDocumentConverter converter = new StringToFlowDocumentConverter(); //first determine if richtextbox document is empty... if so add first paragraph if (richTextBox.Document.Blocks.Count == 0) { richTextBox.Document.Blocks.Add(new Paragraph()); } TextPointer insertionPosition = richTextBox.CaretPosition.GetInsertionPosition(LogicalDirection.Forward); Paragraph currentParagraph = insertionPosition.Paragraph; using (StringReader reader = new StringReader(text)) { string newLine; bool firstLine = true; while ((newLine = reader.ReadLine()) != null) { //if this is first line - append it to the existing paragraph in document if (firstLine) { converter.AppendTextToParagraph(currentParagraph, newLine); firstLine = false; } else { //all other lines append as new paragraphs to text after first paragraph Paragraph newParagraph = converter.ConvertStringLineToParagraph(newLine); richTextBox.Document.Blocks.InsertAfter(currentParagraph, newParagraph); currentParagraph = newParagraph; } } } }
/// <summary> /// Called when [data setting]. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.Windows.DataObjectSettingDataEventArgs"/> instance containing the event data.</param> private void OnDataSetting(object sender, DataObjectSettingDataEventArgs e) { RichTextBox richTextBox = sender as RichTextBox; if (richTextBox == null) { return; } StringToFlowDocumentConverter converter = new StringToFlowDocumentConverter(); TextSelection selection = richTextBox.Selection; string text = converter.ConvertFlowDocumentDataToStringWithinSelection(selection.Start, selection.End); e.DataObject.SetData(System.Windows.DataFormats.UnicodeText, text); }