Gör så här: Extrahera textinnehållet från en RichTextBox

Det här exemplet visar hur du extraherar innehållet i en RichTextBox som oformaterad text.

Beskriva en RichTextBox-kontroll

Följande XAML-kod (Extensible Application Markup Language) beskriver en namngiven RichTextBox kontroll med enkelt innehåll.

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

Kodexempel med RichTextBox som argument

Följande kod implementerar en metod som tar en RichTextBox som ett argument och returnerar en sträng som representerar oformaterad text i RichTextBox.

Metoden skapar en ny TextRange från innehållet i RichTextBox, med hjälp av ContentStart och ContentEnd för att ange innehållets intervall som ska extraheras. ContentStart- och ContentEnd-egenskaperna returnerar var och en en TextPointeroch är tillgängliga i det underliggande FlowDocument som representerar RichTextBox:s innehåll. TextRange innehåller en textegenskap som returnerar oformaterad text i TextRange som en sträng.

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

Se även