方法 : 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 のプレーン テキスト コンテンツを表す文字列を返すメソッドを実装します。

このメソッドは、抽出するコンテンツの範囲を示す ContentStart および ContentEnd を使用して、RichTextBox のコンテンツから新しい TextRange を作成します。 ContentStart プロパティと ContentEnd プロパティはそれぞれ 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 の概要