Практическое руководство. Извлечение текстового содержимого из элемента управления RichTextBox
В этом примере демонстрируется способ извлечения содержимого RichTextBox в виде обычного текста.
Пример
В следующем коде Extensible Application Markup Language (XAML) описывается элемент управления RichTextBox с простым содержимым.
<RichTextBox Name="richTB">
<FlowDocument>
<Paragraph>
<Run>Paragraph 1</Run>
</Paragraph>
<Paragraph>
<Run>Paragraph 2</Run>
</Paragraph>
<Paragraph>
<Run>Paragraph 3</Run>
</Paragraph>
</FlowDocument>
</RichTextBox>
Следующий код реализует метод, который принимает RichTextBox в качестве аргумента и возвращает строку, представляющую текстовое содержимое RichTextBox.
Метод создает новый объект TextRange из содержимого RichTextBox с помощью свойств ContentStart и ContentEnd для указания диапазона извлекаемого содержимого. Каждое из свойств ContentStart и ContentEnd возвращает TextPointer и доступно в основном FlowDocument, представляющем содержимое RichTextBox. TextRange предоставляет свойство Text, которое возвращает часть обычного текста TextRange в виде строки.
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;
}