نظرة عامة على RichTextBox

RichTextBox يمكّن عنصر التحكم عرض أو تحرير تدفق المحتوى بما في ذلك الفقرات و الصور و الجداول و أكثر. يُقدم هذا الموضوع فئة TextBox و يوفر أمثلة عن كيفية استخدامه في Extensible Application Markup Language (XAML) و #C.

يشتمل هذا الموضوع على الأقسام التالية.

  • TextBox أو RichTextBox؟
  • إنشاء RichTextBox
  • ‏‫التدقيق الإملائي في وقت التشغيل
  • قائمة السياق
  • أوامر التحرير
  • الكشف عند حدوث تغييرات في المحتوى
  • حفظ ، و تحميل ، و طباعة محتوى RichTextBox
  • موضوعات ذات صلة

TextBox أو RichTextBox؟

كلا RichTextBox و TextBox السماح للمستخدمين بتحرير نص ، على الرغم من ذلك، يتم استخدام عنصري التحكم في وحدات سيناريو مختلفة. RichTextBox هو خيار أفضل عندما يكون ذلك ضرورياً للمستخدم لتحرير نص منسق أو الصور أو الجداول أو المحتوى الغني الأخر. على سبيل المثال، تحرير المستند أو المقالة أو المدوّنة الذي يتطلب تنسيق أو صور أو غيرها يُنجز أفضل باستخدام RichTextBox. TextBoxيتطلب أقل موارد النظام ثم RichTextBoxو هو مناسب عند تحرير نص عادي فقط (على سبيل المثال الاستخدام في النماذج). راجعنظرة عامة حول مربع نص لمزيد من المعلومات عن TextBox. يلخص الجدول التالي الميزات الأساسية ل TextBox و RichTextBox.

عنصر التحكم

‏‫التدقيق الإملائي في وقت التشغيل

قائمة السياق

تنسيق الأوامر مثل ToggleBold (Ctr + B)

محتوي FlowDocument مثل الصور، الفقرات، جداول، ألخ.

TextBox

نعم

نعم

لا

لا

RichTextBox

نعم

نعم

نعم

نعم

ملاحظة:على الرغم من أن [T:System.Windows.Controls.TextBoxلايدعمأوامرتنسيقالتحريرذاتالصلةمثل][P:System.Windows.Documents.EditingCommands.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 هو تدفق محتوى. يمكن أن يحتوي تدفق المحتوى على العديد من أنواع العناصر بما في ذلك النص المنسق و الصور و القوائم و الجداول. راجع نظرة عامة على مستند التدفق للحصول على معلومات عميقة على مستندات التدفق. من أجل احتواء محتوى التدفق RichTextBox يستضيف FlowDocument الكائن الذي بدوره يحتوي على محتوى قابل للتحرير. لعرض محتوى التدفق في 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 به محتوى

عناصر مثل Paragraph و Bold تحدد كيفية ظهور المحتوى داخل RichTextBox. أثناء قيام المستخدم بتحرير RichTextBox المحتوى ، يمكنهم تغيير محتوى التدفق هذا. لمزيد من المعلومات حول ميزات تدفق المحتوى و كيفية التعامل معها, راجع نظرة عامة على مستند التدفق.

**ملاحظة:**محتوى التدفق داخل RichTextBox لا يسلك تماماً مثل محتوى التدفق المضمن في عناصر التحكم الأخرى. على سبيل المثال، هناك أعمدة في RichTextBox وبالتالي لا يوجد تلقائيا سلوك تغيير الحجم. أيضاً، الميزات المضمنة مثل البحث و وضع العرض و تنقل الصفحة و التكبير غير متوفرين داخل RichTextBox.

‏‫التدقيق الإملائي في وقت التشغيل

يمكنك تمكين ‏‫التدقيق الإملائي في الوقت الحقيقي في TextBox أو RichTextBox. عند تشغيل ‏‫التدقيق الإملائي يظهر خط أحمر تحت الكلمات التي بها أخطاء إملائية (راجع الصورة التالية).

مربع نص به تدقيق إملائي

راجع كيفية القيام بما يلي: تمكين تدقيق الإملاء في عنصر التحكم بتحرير النص للتعرف على كيفية تمكين ‏‫التدقيق الإملائي.

قائمة السياق

افتراضياً، كل من TextBox و RichTextBox يحتوي على قائمة سياق التي تظهر عندما يقوم المستخدم بالنقر بزر الماوس الأيمن داخل عنصر التحكم. قائمة السياق تسمح للمستخدم بالقص، نسخ أو لصق (راجع الشكل التوضيحي التالي).

مربع نص به قائمة سياق

يمكنك إنشاء قائمة السياق المخصصة الخاصة بك لتجاوز القائمة الافتراضية. لمزيد من المعلومات، راجع كيفية القيام بما يلي: وضع قائمة السياق المحددة في 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 به شريط أدوات

الكشف عند حدوث تغييرات في المحتوى

عادةً حدث TextChanged يجب أن يتم استخدامه للكشف كلما النص في TextBox أو RichTextBox تغيير بدلاً من KeyDown كما قد تتوقع. راجع كيفية القيام بما يلي: الكشف عن تغيير النص في مربع نص لمثال.

حفظ ، و تحميل ، و طباعة محتوى 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");
            }
        }
    }
}

راجع أيضًا:

المبادئ

نظرة عامة حول مربع نص

موارد أخرى

المواضيع الإجرائية الخاصة ب RichTextBox