この例では、RichTextBox の内容をプレーン テキストとして抽出する方法を示します。
RichTextBox コントロールについて説明する
次の拡張アプリケーション マークアップ言語 (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 と RichTextBox を使用して、抽出するコンテンツの範囲を示すために、ContentStartの内容から新しい ContentEnd を作成します。 ContentStart プロパティと ContentEnd プロパティはそれぞれ TextPointerを返し、RichTextBoxの内容を表す基になる FlowDocument でアクセスできます。 TextRange は、文字列として TextRange のプレーン テキスト部分を返す Text プロパティを提供します。
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