Como: Extract the Text Content from a RichTextBox
This example shows how to extract the contents of a RichTextBox as plain text.
Exemplo
The following Extensible Application Markup Language (XAML) code describes a named RichTextBox control with simple content.
<RichTextBox Name="richTB">
<FlowDocument>
<Paragraph>
<Run>Paragraph 1</Run>
</Paragraph>
<Paragraph>
<Run>Paragraph 2</Run>
</Paragraph>
<Paragraph>
<Run>Paragraph 3</Run>
</Paragraph>
</FlowDocument>
</RichTextBox>
The following code implements a method that takes a RichTextBox as an argument, and returns a string representing the plain text contents of the RichTextBox.
O método cria uma nova TextRange partir do conteúdo da RichTextBox, usando o ContentStart e ContentEnd para indicar o intervalo do conteúdo para extrair. ContentStarte ContentEnd cada propriedades retornam um TextPointere são acessíveis de FlowDocument subjacente que representa o conteúdo na RichTextBox. TextRangeFornece uma propriedade de texto, que retorna as partes de texto sem formatação a TextRange como uma seqüência de caracteres.
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;
}