Поделиться через


Практическое руководство. Извлечение текстового содержимого из RichTextBox

В этом примере показано, как извлечь содержимое RichTextBox в виде обычного текста.

Описание элемента управления RichTextBox

Следующий код языка разметки приложений (XAML) описывает именованный элемент управления RichTextBox с простым содержимым.

<RichTextBox Name="richTB">
  <FlowDocument>
    <Paragraph>
      <Run>Paragraph 1</Run>
    </Paragraph>
    <Paragraph>
      <Run>Paragraph 2</Run>
    </Paragraph>
    <Paragraph>
      <Run>Paragraph 3</Run>
    </Paragraph>
  </FlowDocument>
</RichTextBox>

Пример кода с RichTextBox в качестве аргумента

Следующий код реализует метод, который принимает RichTextBox в качестве аргумента, и возвращает строку, представляющую текстовое содержимое RichTextBox.

Метод создает новый TextRange из содержимого RichTextBox, используя ContentStart и ContentEnd, чтобы указать диапазон извлекаемого содержимого. ContentStart и ContentEnd свойства возвращают TextPointerи доступны в базовом flowDocument, представляющего содержимое RichTextBox. TextRange предоставляет свойство Text, которое возвращает части обычного текста TextRange в виде строки.

string StringFromRichTextBox(RichTextBox rtb)
{
    TextRange textRange = new TextRange(
        // TextPointer to the start of content in the RichTextBox.
        rtb.Document.ContentStart,
        // TextPointer to the end of content in the RichTextBox.
        rtb.Document.ContentEnd
    );

    // The Text property on a TextRange object returns a string
    // representing the plain text content of the TextRange.
    return textRange.Text;
}
Private Function StringFromRichTextBox(ByVal rtb As RichTextBox) As String
        ' TextPointer to the start of content in the RichTextBox.
        ' TextPointer to the end of content in the RichTextBox.
    Dim textRange As New TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd)

    ' The Text property on a TextRange object returns a string
    ' representing the plain text content of the TextRange.
    Return textRange.Text
End Function

См. также