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

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

Ejemplo

En el código Extensible Application Markup Language (XAML) siguiente se 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>

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

El método crea un nuevo objeto TextRange a partir del contenido de RichTextBox, utilizando las propiedades ContentStart y ContentEnd para indicar el intervalo de contenido que se va a extraer. Las propiedades ContentEnd y ContentStart devuelven un objetoTextPointer cada una, y están accesibles en el objeto 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.

        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
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;
}

Vea también

Conceptos

Información general sobre el control RichTextBox

Información general sobre TextBox