Partager via


Comment : extraire le texte d'un RichTextBox

Cet exemple montre comment extraire le contenu d’un RichTextBox texte brut.

Décrire un contrôle RichTextBox

Le code XAML (Extensible Application Markup Language) suivant décrit un contrôle nommé RichTextBox avec du contenu 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>

Exemple de code avec RichTextBox en tant qu’argument

Le code suivant implémente une méthode qui prend un RichTextBox argument et retourne une chaîne représentant le contenu de texte brut du RichTextBox.

La méthode crée une nouvelle TextRange à partir du contenu du RichTextBox, à l’aide ContentStart du et ContentEnd pour indiquer la plage du contenu à extraire. ContentStart et ContentEnd les propriétés retournent un TextPointer, et sont accessibles sur le FlowDocument sous-jacent qui représente le contenu du RichTextBox. TextRange fournit une propriété Text, qui retourne les parties de texte brut de la TextRange sous forme de chaîne.

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

Voir aussi