此示例演示如何将 RichTextBox 的内容提取为纯文本。
描述 RichTextBox 控件
以下可扩展应用程序标记语言 (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 作为参数,并返回表示 RichTextBox纯文本内容的字符串。
使用 ContentStart 和 ContentEnd 来指示要提取的内容范围,该方法从 RichTextBox的内容中创建一个新的 TextRange。 ContentStart 和 ContentEnd 属性各自返回了一个 TextPointer,并且可以在表示 RichTextBox 内容的基础 FlowDocument 上访问。 TextRange 提供一个 Text 属性,该属性将 TextRange 的纯文本部分作为字符串返回。
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