다음을 통해 공유


방법: RichTextBox에서 텍스트 콘텐츠 추출

이 예제에서는 일반 텍스트로 RichTextBox의 콘텐츠를 추출하는 방법을 보여 줍니다.

RichTextBox 컨트롤 설명

다음 XAML(Extensible Application Markup Language) 코드는 간단한 콘텐츠가 있는 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의 일반 텍스트 부분을 반환하는 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

참고하십시오