如何:从 RichTextBox 提取文本内容

此示例演示如何将 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字符串。

该方法通过使用ContentStartContentEnd来指示要提取的内容范围,从RichTextBox的内容中创建一个新的TextRangeContentStartContentEnd 属性每个返回一个 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

另请参阅