Общие сведения о RichTextBox

Элемент управления RichTextBox позволяет отображать или изменять содержимое нефиксированного формата, включая абзацы, изображения, таблицы и др. В этом разделе представлены сведения о классе TextBox и приведены примеры его использования как в XAML, так и на C#.

TextBox или RichTextBox?

Оба элемента управления RichTextBox и TextBox позволяют пользователям изменять текст, но они используются в различных сценариях. Если пользователю необходимо отредактировать форматированный текст, изображения, таблицы или другое форматированное содержимое, лучше использовать элемент управления RichTextBox. Например, редактирование документа, статьи или блога, для которых требуется форматирование, рисунки, и т. д., лучше всего выполнять с помощью элемента управления RichTextBox. Для элемента управления TextBox требуется меньший объем системных ресурсов по сравнению с RichTextBox, и он идеально подходит для тех случаев, когда необходимо редактировать только обычный текст (например, в формах). Дополнительные сведения об элементе управления TextBox см. в разделе Общие сведения об элементе управления TextBox. В приведенной ниже таблице перечислены основные функции элементов управления TextBox и RichTextBox.

Элемент управления Проверка орфографии в режиме реального времени Контекстное меню Команды форматирования, например, ToggleBold (CTRL+B) Содержимое FlowDocument, такое как изображения, абзацы, таблицы и т. д.
TextBox Да Да No Нет.
RichTextBox Да Да Да Да

Примечание.

Хотя элемент управления TextBox не поддерживает команды форматирования, такие как ToggleBold (CTRL+B), многие базовые команды, например, MoveToLineEnd поддерживаются обоими элементами управления.

Функции из приведенной выше таблицы будут подробно рассматриваться далее.

Создание элемента управления RichTextBox

В следующем примере кода показано, как создать элемент управления RichTextBox, в котором пользователь может редактировать форматированное содержимое.

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

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

</Page>

В частности, содержимое, редактируемое в элементе управления RichTextBox, имеет нефиксированный формат. Содержимое нефиксированного формата может включать множество типов элементов, в том числе форматированный текст, изображения, списки и таблицы. См. более подробные сведения о потоковых документах в разделе Общие сведения о потоковых документах. Чтобы в элементе управления RichTextBox можно было размещать содержимое нефиксированного формата, он содержит объект FlowDocument, который в свою очередь содержит редактируемое содержимое. Чтобы продемонстрировать содержимое нефиксированного формата в элементе управления RichTextBox, воспользуйтесь следующим примером кода, в котором показано, как создать элемент управления RichTextBox с абзацем, часть текста в котором выделена полужирным.

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://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>
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;
        }
    }
}

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

На рисунке ниже показано, как будет выглядеть этот пример.

RichTextBox with content

Такие элементы как Paragraph и Bold определяют, как отображается содержимое внутри элемента управления RichTextBox. По мере того, как пользователь редактирует содержимое RichTextBox, он изменяет это содержимое нефиксированного формата. Дополнительные сведения о возможностях подвижного содержимого и способах работы с ним см. в разделе Общие сведения о потоковых документах.

Примечание.

Содержимое нефиксированного формата внутри элемента управления RichTextBox ведет себя не так, как в других элементах управления. Например, в RichTextBox отсутствуют столбцы, и поэтому автоматическое изменение размеров не выполняется. Кроме того, встроенные функции, такие как поиск, режим просмотра, навигация по страницам и увеличение, недоступны в элементе управления RichTextBox.

Проверка орфографии в режиме реального времени

Вы можете включить проверку орфографии в реальном времени для элементов управления TextBox и RichTextBox. При включенной проверке орфографии все слова с ошибками подчеркиваются красной линией (см. рисунок ниже).

Textbox with spell-checking

Чтобы научиться включать проверку правописания, см. раздел Включение проверки орфографии в элементе управления редактирования текста.

Контекстное меню

По умолчанию элементы управления TextBox и RichTextBox имеют контекстное меню, которое отображается при щелчке пользователя правой кнопкой мыши внутри элемента управления. Контекстное меню дает пользователю возможность вырезания, копирования и вставки (см. рисунок ниже).

TextBox with context menu

Можно создать собственное пользовательское контекстное меню, чтобы переопределить меню по умолчанию. Дополнительные сведения см. в разделе Расположение пользовательского контекстного меню в RichTextBox.

Команды изменения

Команды редактирования дают пользователям возможность форматировать редактируемое содержимое в RichTextBox. Наряду с базовыми командами редактирования RichTextBox включает команды форматирования, не поддерживаемые элементом управления TextBox. Например, при редактировании в RichTextBox пользователь может нажать CTRL+B, чтобы сделать текст полужирным или превратить текст из полужирного в обычный. Полный список команд см. в разделе EditingCommands. Помимо использования сочетания клавиш, можно подключать команды к другим элементам управления, таким как кнопки. В следующем примере показано, как создать простую панель инструментов, содержащую кнопки, с помощью которых пользователь может изменять форматирование текста.

<Window x:Class="RichTextBoxInputPanelDemo.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://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 with ToolBar

Определение изменения содержимого

Обычно для того, чтобы определить изменение текста в элементах управления TextBox и RichTextBox используется событие TextChanged, а не KeyDown, как можно было ожидать. Пример см. в разделе Определение изменения текста в TextBox.

Сохранение, загрузка и печать содержимого RichTextBox

В следующем примере показано, как сохранить содержимое RichTextBox в файл, как загрузить это содержимое обратно в RichTextBox и как распечатать содержимое. Ниже для примера приведена разметка.

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://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>

Ниже для примера приведен код.

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");
            }
        }
    }
}

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

См. также