方法: 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 を作成し、ContentStart と ContentEnd を使用して、抽出するコンテンツの範囲を示します。 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
関連項目
GitHub で Microsoft と共同作業する
このコンテンツのソースは GitHub にあります。そこで、issue や pull request を作成および確認することもできます。 詳細については、共同作成者ガイドを参照してください。
.NET Desktop feedback
フィードバック
https://aka.ms/ContentUserFeedback」を参照してください。
以下は間もなく提供いたします。2024 年を通じて、コンテンツのフィードバック メカニズムとして GitHub の issue を段階的に廃止し、新しいフィードバック システムに置き換えます。 詳細については、「フィードバックの送信と表示