Share via


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

このメソッドでは、RichTextBox のコンテンツから新しい TextRange を作成し、ContentStartContentEnd を使用して、抽出するコンテンツの範囲を示します。 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

関連項目