Vue d'ensemble de RichTextBox

Le RichTextBox contrôle vous permet d’afficher ou de modifier du contenu de flux, notamment des paragraphes, des images, des tableaux, etc. Cette rubrique présente la TextBox classe et fournit des exemples d’utilisation dans XAML (Extensible Application Markup Language) et C#.

TextBox ou RichTextBox ?

Toutefois, les RichTextBox deux contrôles sont utilisés dans différents scénarios et TextBox permettent aux utilisateurs de modifier du texte. Un RichTextBox meilleur choix s’il est nécessaire à l’utilisateur de modifier du texte mis en forme, des images, des tableaux ou d’autres contenus enrichis. Par exemple, la modification d’un document, d’un article ou d’un blog nécessitant une mise en forme, des images, etc. est optimale à l’aide d’un RichTextBox. Une TextBox ressource système nécessite moins de ressources système qu’une RichTextBox et il est idéal lorsque seul le texte brut doit être modifié (c’est-à-dire l’utilisation dans les formulaires). Consultez La vue d’ensemble de TextBox pour plus d’informations sur TextBox. Le tableau ci-dessous récapitule les principales fonctionnalités de TextBox et RichTextBox.

Contrôler Vérification de l’orthographe en temps réel Menu contextuel Commandes de mise en forme comme ToggleBold (Ctr+B) FlowDocument contenu comme des images, des paragraphes, des tableaux, etc.
TextBox Oui Oui Non Nombre
RichTextBox Oui Oui Oui Oui

Remarque

Bien que TextBox ne prend pas en charge la mise en forme des commandes associées comme ToggleBold (Ctr+B), de nombreuses commandes de base sont prises en charge par les deux contrôles tels que MoveToLineEnd.

Les fonctionnalités du tableau ci-dessus sont présentées plus en détail dans la suite de ce document.

Création d’un contrôle RichTextBox

Le code ci-dessous montre comment créer un RichTextBox élément dans lequel un utilisateur peut modifier du contenu enrichi.

<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>

Plus précisément, le contenu modifié dans un RichTextBox flux est contenu. Le contenu dynamique peut contenir de nombreux types d’éléments, notamment du texte mis en forme, des images, des listes et des tableaux. Pour obtenir des informations complètes sur les documents dynamiques, consultez Vue d’ensemble des documents dynamiques. Pour contenir du contenu de flux, un RichTextBox objet héberge FlowDocument à son tour le contenu modifiable. Pour illustrer le contenu de flux dans un RichTextBoxcode suivant, le code suivant montre comment créer un RichTextBox paragraphe avec un paragraphe et un texte en gras.

<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

L’illustration suivante montre le rendu de cet exemple.

RichTextBox with content

Les éléments tels Paragraph que et Bold déterminent la façon dont le contenu à l’intérieur d’un RichTextBox apparaît. En tant qu’utilisateur modifie le RichTextBox contenu, il modifie ce contenu de flux. Pour en savoir plus sur les fonctionnalités et l’utilisation du contenu dynamique, consultez Vue d’ensemble des documents dynamiques.

Remarque

Le contenu de flux à l’intérieur d’un ne RichTextBox se comporte pas exactement comme le contenu de flux contenu dans d’autres contrôles. Par exemple, il n’existe aucune colonne dans un RichTextBox comportement de redimensionnement automatique. En outre, les fonctionnalités intégrées telles que la recherche, le mode d’affichage, la navigation de page et le zoom ne sont pas disponibles dans un RichTextBox.

Vérification de l’orthographe en temps réel

Vous pouvez activer le case activée orthographique en temps réel dans un TextBox ou RichTextBox. Lorsque la vérification de l’orthographe est activée, une ligne rouge apparaît sous les mots mal orthographiés (voir l’illustration ci-dessous).

Textbox with spell-checking

Pour savoir comment activer la vérification de l’orthographe, consultez Activer la vérification de l’orthographe dans un contrôle d’édition de texte.

Menu contextuel

Par défaut, vous disposez à la fois TextBox d’un RichTextBox menu contextuel qui s’affiche lorsqu’un utilisateur clique avec le bouton droit dans le contrôle. Ce menu contextuel permet à l’utilisateur de couper, de copier ou de coller du texte (voir l’illustration ci-dessous).

TextBox with context menu

Vous pouvez créer votre propre menu contextuel personnalisé pour remplacer celui par défaut. Pour plus d’informations, consultez Positionner un menu contextuel personnalisé dans un RichTextBox.

Commandes d’édition

Les commandes d’édition permettent aux utilisateurs de mettre en forme du contenu modifiable à l’intérieur d’un RichTextBox. Outre les commandes d’édition de base, RichTextBox inclut des commandes de mise en forme qui TextBox ne prennent pas en charge. Par exemple, lors de la modification dans un RichTextBox, un utilisateur peut appuyer sur Ctr+B pour activer la mise en forme de texte en gras. Consultez EditingCommands la liste complète des commandes disponibles. Outre l’utilisation des raccourcis clavier, vous pouvez associer des commandes à d’autres contrôles, notamment des boutons. L’exemple suivant montre comment créer une barre d’outils simple contenant des boutons que l’utilisateur peut utiliser pour modifier la mise en forme du texte.

<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>

L’illustration suivante montre comment cet exemple s’affiche.

RichTextBox with ToolBar

Détecter la modification du contenu

En règle générale, l’événement TextChanged doit être utilisé pour détecter chaque fois que le texte d’une ou RichTextBox de TextBox plusieurs modifications est alors KeyDown attendu. Pour obtenir un exemple, consultez Détecter la modification du texte figurant dans un TextBox.

Enregistrer, charger et imprimer le contenu d'un RichTextBox

L’exemple suivant montre comment enregistrer le contenu d’un RichTextBox fichier, charger ce contenu dans le RichTextBoxfichier et imprimer le contenu. Voici le balisage de l’exemple.

<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>

Voici le code-behind de l’exemple.

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

Voir aussi