Condividi tramite


Procedura: estrarre il contenuto di testo da un oggetto RichTextBox

In questo esempio viene illustrato come estrarre il contenuto di un oggetto RichTextBox come testo normale.

Descrivere un controllo RichTextBox

Il codice XAML (Extensible Application Markup Language) seguente descrive un controllo denominato RichTextBox con contenuto semplice.

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

Esempio di codice con RichTextBox come argomento

Il codice seguente implementa un metodo che accetta come RichTextBox argomento e restituisce una stringa che rappresenta il contenuto di testo normale dell'oggetto RichTextBox.

Il metodo crea un nuovo TextRange oggetto dal contenuto di RichTextBox, utilizzando ContentStart e ContentEnd per indicare l'intervallo del contenuto da estrarre. ContentStart e ContentEnd le proprietà restituiscono e TextPointersono accessibili in FlowDocument sottostante che rappresenta il contenuto dell'oggetto RichTextBox. TextRange fornisce una proprietà Text, che restituisce le parti di testo normale di TextRange come stringa.

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

Vedi anche