다음을 통해 공유


RichTextBox 개요

RichTextBox 컨트롤을 사용하면 단락, 이미지, 표 등을 비롯한 유동 콘텐츠를 표시하거나 편집할 수 있습니다. 이 항목에서는 TextBox 클래스를 소개하고 Extensible Application Markup Language (XAML) 및 C#에서 이 클래스를 사용하는 방법에 대한 예제를 제공합니다.

이 항목에는 다음 단원이 포함되어 있습니다.

  • TextBox 또는 RichTextBox?
  • RichTextBox 만들기
  • 실시간 맞춤법 검사
  • 상황에 맞는 메뉴
  • 편집 명령
  • 콘텐츠가 변경되는 시점 감지
  • RichTextBox 콘텐츠 저장, 로드 및 인쇄
  • 관련 항목

TextBox 또는 RichTextBox?

RichTextBoxTextBox에서는 사용자가 텍스트를 편집하는 것이 모두 허용되지만 다른 시나리오에서 두 개의 컨트롤이 사용됩니다. 서식 있는 텍스트, 이미지, 표 또는 기타 풍부한 콘텐츠를 편집해야 할 경우에는 RichTextBox가 더 적합합니다. 예를 들어 서식, 이미지 등이 필요한 문서, 기사 또는 블로그를 편집할 때는 RichTextBox를 사용하는 것이 가장 좋습니다. TextBox에는 RichTextBox보다 적은 시스템 리소스가 필요하므로 일반 텍스트만 편집해야 하는 경우(예: 폼에서 사용)에 적합합니다. TextBox에 대한 자세한 내용은 TextBox 개요를 참조하십시오. 아래 표에서는 TextBoxRichTextBox의 기본 기능을 요약하여 보여 줍니다.

컨트롤

실시간 맞춤법 검사

상황에 맞는 메뉴

ToggleBold(Ctr+B)와 같은 서식 명령

이미지, 단락, 표 등과 같은 FlowDocument 콘텐츠

TextBox

아니요

아니요.

RichTextBox

참고: TextBox에서는 ToggleBold(Ctr+B)와 같은 서식 관련 명령이 지원되지 않지만 MoveToLineEnd와 같은 대부분의 기본 명령은 두 컨트롤 모두에서 지원됩니다.

위 표의 기능은 뒷부분에서 자세히 설명합니다.

RichTextBox 만들기

아래 코드에서는 사용자가 풍부한 콘텐츠를 편집할 수 있는 RichTextBox를 만드는 방법을 보여 줍니다.

<Page xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml">

    <!-- A RichTextBox with no initial content in it. -->
    <RichTextBox />

</Page>

특히 RichTextBox에서 편집된 콘텐츠는 유동 콘텐츠입니다. 유동 콘텐츠에는 서식 있는 텍스트, 이미지, 목록 및 표를 비롯하여 요소의 많은 형식이 포함될 수 있습니다. 유동 문서에 대한 자세한 내용은 유동 문서 개요를 참조하십시오. 유동 콘텐츠를 포함할 수 있도록 RichTextBoxFlowDocument 개체를 호스팅하고 이 개체에는 편집 가능한 콘텐츠가 포함됩니다. RichTextBox의 유동 콘텐츠를 설명하기 위해 다음 코드에서는 단락 및 몇 개의 굵게 표시된 텍스트를 사용하여 RichTextBox를 만드는 방법을 보여 줍니다.

<Page xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml">

  <StackPanel>
    <RichTextBox>
      <FlowDocument>
        <Paragraph>
          This is flow content and you can <Bold>edit me!</Bold>
        </Paragraph>
      </FlowDocument>
    </RichTextBox>
  </StackPanel>

</Page>

Imports System
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Media
Imports System.Windows.Documents
Namespace SDKSample
    Partial Public Class BasicRichTextBoxWithContentExample
        Inherits Page
        Public Sub New()
            Dim myStackPanel As New StackPanel()

            ' Create a FlowDocument to contain content for the RichTextBox.
            Dim myFlowDoc As New FlowDocument()

            ' Create a Run of plain text and some bold text.
            Dim myRun As New Run("This is flow content and you can ")
            Dim myBold As New Bold(New Run("edit me!"))

            ' Create a paragraph and add the Run and Bold to it.
            Dim myParagraph As New Paragraph()
            myParagraph.Inlines.Add(myRun)
            myParagraph.Inlines.Add(myBold)

            ' Add the paragraph to the FlowDocument.
            myFlowDoc.Blocks.Add(myParagraph)

            Dim myRichTextBox As New RichTextBox()

            ' Add initial content to the RichTextBox.
            myRichTextBox.Document = myFlowDoc

            myStackPanel.Children.Add(myRichTextBox)
            Me.Content = myStackPanel

        End Sub
    End Class
End Namespace
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Documents;
namespace SDKSample
{
    public partial class BasicRichTextBoxWithContentExample : Page
    {
        public BasicRichTextBoxWithContentExample()
        {
            StackPanel myStackPanel = new StackPanel();

            // Create a FlowDocument to contain content for the RichTextBox.
            FlowDocument myFlowDoc = new FlowDocument();

            // Create a Run of plain text and some bold text.
            Run myRun = new Run("This is flow content and you can ");
            Bold myBold = new Bold(new Run("edit me!"));

            // Create a paragraph and add the Run and Bold to it.
            Paragraph myParagraph = new Paragraph();
            myParagraph.Inlines.Add(myRun);
            myParagraph.Inlines.Add(myBold);

            // Add the paragraph to the FlowDocument.
            myFlowDoc.Blocks.Add(myParagraph);

            RichTextBox myRichTextBox = new RichTextBox();

            // Add initial content to the RichTextBox.
            myRichTextBox.Document = myFlowDoc;

            myStackPanel.Children.Add(myRichTextBox);
            this.Content = myStackPanel;

        }
    }
}

다음 그림에서는 이 샘플이 렌더링되는 방식을 보여 줍니다.

콘텐츠가 있는 RichTextBox

ParagraphBold와 같은 요소는 RichTextBox 내의 콘텐츠가 표시되는 방식을 결정합니다. 사용자가 RichTextBox 콘텐츠를 편집하면 이 유동 콘텐츠가 변경됩니다. 유동 콘텐츠의 기능 및 그 사용 방법에 대한 자세한 내용은 유동 문서 개요를 참조하십시오.

참고: RichTextBox 내의 유동 콘텐츠는 다른 컨트롤에 포함된 유동 콘텐츠와 동일하게 작동하지 않습니다. 예를 들어 RichTextBox에는 열이 없으므로 자동 크기 조정 동작이 발생하지 않습니다. 또한 검색, 보기 모드, 페이지 탐색, 확대/축소 등과 같은 기본 제공 기능을 RichTextBox 내에서 사용할 수 없습니다.

실시간 맞춤법 검사

TextBox 또는 RichTextBox에서 실시간 맞춤법 검사를 설정할 수 있습니다. 맞춤법 검사가 설정된 경우 맞춤법이 틀린 모든 단어 아래에 빨간색 줄이 나타납니다(아래 그림 참조).

맞춤법 검사 기능이 있는 Textbox

맞춤법 검사를 사용하도록 설정하는 방법은 방법: 텍스트 편집 컨트롤에서 맞춤법 검사 사용을 참조하십시오.

상황에 맞는 메뉴

기본적으로 TextBoxRichTextBox 모두에는 사용자가 컨트롤 안에서 마우스 오른쪽 단추를 클릭했을 때 표시되는 상황에 맞는 메뉴가 있습니다. 상황에 맞는 메뉴를 사용하여 잘라내기, 복사 또는 붙여넣기를 수행할 수 있습니다(아래 그림 참조).

상황에 맞는 메뉴가 있는 TextBox

사용자 지정된 고유한 상황에 맞는 메뉴를 만들어 기본 메뉴를 재정의할 수 있습니다. 자세한 내용은 방법: RichTextBox에서 사용자 지정 상황에 맞는 메뉴의 위치 지정을 참조하십시오.

편집 명령

편집 명령을 사용하면 RichTextBox 내에서 편집 가능한 콘텐츠의 서식을 지정할 수 있습니다. 기본 편집 명령 외에 RichTextBox에는 TextBox에서 지원하지 않는 서식 지정 명령이 포함됩니다. 예를 들어 RichTextBox에서 편집할 때 사용자는 Ctr+B를 눌러 굵은 텍스트 서식을 전환할 수 있습니다. 사용할 수 있는 명령의 전체 목록을 보려면 EditingCommands를 참조하십시오. 바로 가기 키를 사용하는 것 외에도 단추 같은 다른 컨트롤에 명령을 후크할 수 있습니다. 다음 예제에서는 사용자가 텍스트 서식 변경에 사용할 수 있는 단추가 포함된 간단한 도구 모음을 만드는 방법을 보여 줍니다.

<Window x:Class="RichTextBoxInputPanelDemo.Window1"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" Height="400" Width="600"
    >
  <Grid>

    <!-- Set the styles for the tool bar. -->
    <Grid.Resources>
      <Style TargetType="{x:Type Button}" x:Key="formatTextStyle">
        <Setter Property="FontFamily" Value="Palatino Linotype"></Setter>
        <Setter Property="Width" Value="30"></Setter>
        <Setter Property="FontSize" Value ="14"></Setter>
        <Setter Property="CommandTarget" Value="{Binding ElementName=mainRTB}"></Setter>
      </Style>

      <Style TargetType="{x:Type Button}" x:Key="formatImageStyle">
        <Setter Property="Width" Value="30"></Setter>
        <Setter Property="CommandTarget" Value="{Binding ElementName=mainRTB}"></Setter>
      </Style>
    </Grid.Resources>

    <DockPanel Name="mainPanel">

      <!-- This tool bar contains all the editing buttons. -->
      <ToolBar Name="mainToolBar" Height="30" DockPanel.Dock="Top">

        <Button Style="{StaticResource formatImageStyle}" Command="ApplicationCommands.Cut" ToolTip="Cut">
          <Image Source="Images\EditCut.png"></Image>
        </Button>
        <Button Style="{StaticResource formatImageStyle}" Command="ApplicationCommands.Copy" ToolTip="Copy">
          <Image Source="Images\EditCopy.png"></Image>
        </Button>
        <Button Style="{StaticResource formatImageStyle}" Command="ApplicationCommands.Paste" ToolTip="Paste">
          <Image Source="Images\EditPaste.png"></Image>
        </Button>
        <Button Style="{StaticResource formatImageStyle}" Command="ApplicationCommands.Undo" ToolTip="Undo">
          <Image Source="Images\EditUndo.png"></Image>
        </Button>
        <Button Style="{StaticResource formatImageStyle}" Command="ApplicationCommands.Redo" ToolTip="Redo">
          <Image Source="Images\EditRedo.png"></Image>
        </Button>

        <Button Style="{StaticResource formatTextStyle}" Command="EditingCommands.ToggleBold" ToolTip="Bold">
          <TextBlock FontWeight="Bold">B</TextBlock>
        </Button>
        <Button Style="{StaticResource formatTextStyle}" Command="EditingCommands.ToggleItalic" ToolTip="Italic">
          <TextBlock FontStyle="Italic" FontWeight="Bold">I</TextBlock>
        </Button>
        <Button Style="{StaticResource formatTextStyle}" Command="EditingCommands.ToggleUnderline" ToolTip="Underline">
          <TextBlock TextDecorations="Underline" FontWeight="Bold">U</TextBlock>
        </Button>
        <Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.IncreaseFontSize" ToolTip="Grow Font">
          <Image Source="Images\CharacterGrowFont.png"></Image>
        </Button>
        <Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.DecreaseFontSize" ToolTip="Shrink Font">
          <Image Source="Images\CharacterShrinkFont.png"></Image>
        </Button>

        <Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.ToggleBullets" ToolTip="Bullets">
          <Image Source="Images\ListBullets.png"></Image>
        </Button>
        <Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.ToggleNumbering" ToolTip="Numbering">
          <Image Source="Images/ListNumbering.png"></Image>
        </Button>
        <Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.AlignLeft" ToolTip="Align Left">
          <Image Source="Images\ParagraphLeftJustify.png"></Image>
        </Button>
        <Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.AlignCenter" ToolTip="Align Center">
          <Image Source="Images\ParagraphCenterJustify.png"></Image>
        </Button>
        <Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.AlignRight" ToolTip="Align Right">
          <Image Source="Images\ParagraphRightJustify.png"></Image>
        </Button>
        <Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.AlignJustify" ToolTip="Align Justify">
          <Image Source="Images\ParagraphFullJustify.png"></Image>
        </Button>
        <Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.IncreaseIndentation" ToolTip="Increase Indent">
          <Image Source="Images\ParagraphIncreaseIndentation.png"></Image>
        </Button>
        <Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.DecreaseIndentation" ToolTip="Decrease Indent">
          <Image Source="Images\ParagraphDecreaseIndentation.png"></Image>
        </Button>

      </ToolBar>

      <!-- By default pressing tab moves focus to the next control. Setting AcceptsTab to true allows the 
           RichTextBox to accept tab characters. -->
      <RichTextBox Name="mainRTB" AcceptsTab="True"></RichTextBox>
    </DockPanel>
  </Grid>
</Window>

다음 그림에서는 이 샘플이 표시되는 방식을 보여 줍니다.

도구 모음이 있는 RichTextBox

콘텐츠가 변경되는 시점 감지

일반적으로 TextBox 또는 RichTextBox의 텍스트가 변경되는 시점을 감지하려면 예상과 달리 KeyDown이 아닌 TextChanged 이벤트를 사용해야 합니다. 예제는 방법: TextBox에서 텍스트가 변경되는 시점 감지를 참조하십시오.

RichTextBox 콘텐츠 저장, 로드 및 인쇄

다음 예제에서는 RichTextBox의 콘텐츠를 파일에 저장하고 이를 다시 RichTextBox에 로드하며 해당 콘텐츠를 인쇄하는 방법을 보여 줍니다. 다음은 예제의 태그입니다.

<Page xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
  x:Class="SDKSample.SaveLoadPrintRTB" >

  <StackPanel>
    <RichTextBox Name="richTB">
      <FlowDocument>
        <Paragraph>
          <Run>Paragraph 1</Run>
        </Paragraph>
      </FlowDocument>
    </RichTextBox>

    <Button Click="SaveRTBContent">Save RTB Content</Button>
    <Button Click="LoadRTBContent">Load RTB Content</Button>
    <Button Click="PrintRTBContent">Print RTB Content</Button>
  </StackPanel>

</Page>

다음은 예제의 코드 숨김입니다.


Imports System
Imports System.IO
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Documents
Imports System.Windows.Media

Namespace SDKSample

    Partial Public Class SaveLoadPrintRTB
        Inherits Page

        ' Handle "Save RichTextBox Content" button click.
        Private Sub SaveRTBContent(ByVal sender As Object, ByVal args As RoutedEventArgs)

            ' Send an arbitrary URL and file name string specifying
            ' the location to save the XAML in.
            SaveXamlPackage("C:\test.xaml")
        End Sub

        ' Handle "Load RichTextBox Content" button click.
        Private Sub LoadRTBContent(ByVal sender As Object, ByVal args As RoutedEventArgs)
            ' Send URL string specifying what file to retrieve XAML
            ' from to load into the RichTextBox.
            LoadXamlPackage("C:\test.xaml")
        End Sub

        ' Handle "Print RichTextBox Content" button click.
        Private Sub PrintRTBContent(ByVal sender As Object, ByVal args As RoutedEventArgs)
            PrintCommand()
        End Sub

        ' Save XAML in RichTextBox to a file specified by _fileName
        Private Sub SaveXamlPackage(ByVal _fileName As String)
            Dim range As TextRange
            Dim fStream As FileStream
            range = New TextRange(richTB.Document.ContentStart, richTB.Document.ContentEnd)
            fStream = New FileStream(_fileName, FileMode.Create)
            range.Save(fStream, DataFormats.XamlPackage)
            fStream.Close()
        End Sub

        ' Load XAML into RichTextBox from a file specified by _fileName
        Private Sub LoadXamlPackage(ByVal _fileName As String)
            Dim range As TextRange
            Dim fStream As FileStream
            If File.Exists(_fileName) Then
                range = New TextRange(richTB.Document.ContentStart, richTB.Document.ContentEnd)
                fStream = New FileStream(_fileName, FileMode.OpenOrCreate)
                range.Load(fStream, DataFormats.XamlPackage)
                fStream.Close()
            End If
        End Sub

        ' Print RichTextBox content
        Private Sub PrintCommand()
            Dim pd As New PrintDialog()
            If (pd.ShowDialog() = True) Then
                'use either one of the below      
                pd.PrintVisual(TryCast(richTB, Visual), "printing as visual")
                pd.PrintDocument(((CType(richTB.Document, IDocumentPaginatorSource)).DocumentPaginator), "printing as paginator")
            End If
        End Sub
    End Class
End Namespace
using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

namespace SDKSample
{

    public partial class SaveLoadPrintRTB : Page
    {

        // Handle "Save RichTextBox Content" button click.
        void SaveRTBContent(Object sender, RoutedEventArgs args)
        {

            // Send an arbitrary URL and file name string specifying
            // the location to save the XAML in.
            SaveXamlPackage("C:\\test.xaml");
        }

        // Handle "Load RichTextBox Content" button click.
        void LoadRTBContent(Object sender, RoutedEventArgs args)
        {
            // Send URL string specifying what file to retrieve XAML
            // from to load into the RichTextBox.
            LoadXamlPackage("C:\\test.xaml");
        }

        // Handle "Print RichTextBox Content" button click.
        void PrintRTBContent(Object sender, RoutedEventArgs args)
        {
            PrintCommand();
        }

        // Save XAML in RichTextBox to a file specified by _fileName
        void SaveXamlPackage(string _fileName)
        {
            TextRange range;
            FileStream fStream;
            range = new TextRange(richTB.Document.ContentStart, richTB.Document.ContentEnd);
            fStream = new FileStream(_fileName, FileMode.Create);
            range.Save(fStream, DataFormats.XamlPackage);
            fStream.Close();
        }

        // Load XAML into RichTextBox from a file specified by _fileName
        void LoadXamlPackage(string _fileName)
        {
            TextRange range;
            FileStream fStream;
            if (File.Exists(_fileName))
            {
                range = new TextRange(richTB.Document.ContentStart, richTB.Document.ContentEnd);
                fStream = new FileStream(_fileName, FileMode.OpenOrCreate);
                range.Load(fStream, DataFormats.XamlPackage);
                fStream.Close();
            }
        }

        // Print RichTextBox content
        private void PrintCommand()
        {
            PrintDialog pd = new PrintDialog();
            if ((pd.ShowDialog() == true))
            {
                //use either one of the below      
                pd.PrintVisual(richTB as Visual, "printing as visual");
                pd.PrintDocument((((IDocumentPaginatorSource)richTB.Document).DocumentPaginator), "printing as paginator");
            }
        }
    }
}

참고 항목

개념

TextBox 개요

기타 리소스

RichTextBox 방법 항목