如何:从 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 的纯文本内容的字符串。

该方法从 RichTextBox 的内容创建一个新的 TextRange,并使用 ContentStartContentEnd 指示要提取的内容的范围。 ContentStartContentEnd 属性均返回一个 TextPointer,并且在表示 RichTextBox 内容的基础 FlowDocument 上可以进行访问。 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;
}

请参见

概念

RichTextBox 概述

TextBox 概述