共用方式為


如何:擷取 RichTextBox 的文字內容

此範例顯示如何將 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 純文字內容的字串。

該方法會使用 ContentStartContentEnd,從 RichTextBox 的內容建立新的 TextRange,以表示要擷取的內容範圍。 ContentStartContentEnd 屬性都會傳回 TextPointer,而且可在代表 RichTextBox 內容的基礎 FlowDocument 上存取。 TextRange 提供文字屬性,以字串形式傳回 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

另請參閱