Cómo: Extraer el contenido de texto de un control RichTextBox

En este ejemplo se muestra cómo extraer el contenido de RichTextBox como texto sin formato.

Descripción de un control RichTextBox

El siguiente código XAML (Extensible Application Markup Language) describe un control RichTextBox con nombre con contenido simple.

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

Ejemplo de código con RichTextBox como argumento

El código siguiente implementa un método que toma RichTextBox como argumento y devuelve una cadena que representa el contenido de texto sin formato de RichTextBox.

El método crea un nuevo TextRange a partir del contenido de RichTextBox, utilizando ContentStart y ContentEnd para indicar el rango del contenido que se va a extraer. Las propiedades ContentStart y ContentEnd devuelven TextPointer y son accesibles en el FlowDocument subyacente que representa el contenido de RichTextBox. TextRange proporciona una propiedad Text, que devuelve las partes de texto sin formato de TextRange como una cadena.

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

Vea también