Share via


RichTextBox 概觀

更新:2007 年 11 月

RichTextBox 控制項可讓您顯示或編輯非固定格式內容,包括段落、影像、表格等等。本主題介紹 TextBox 類別,並提供如何在可延伸標記語言 (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 編輯的內容即為非固定格式內容。非固定格式內容可包含許多項目類型,包括格式化文字、影像、清單與表格等。如需非固定格式文件的詳細資訊,請參閱非固定格式文件概觀。若要包含非固定格式內容,RichTextBox 必須裝載 (Host) 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>
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 內並沒有搜尋、檢視模式、頁面巡覽與縮放等內建功能。

即時拼字檢查

您可以在 TextBoxRichTextBox 中啟用即時拼字檢查。啟用拼字檢查時,拼錯的文字下方會出現紅色線條 (請見下圖)。

具有拼字檢查功能的 Textbox

若要了解如何啟用拼字檢查,請參閱 HOW TO:在文字編輯控制項中啟用拼字檢查

內容功能表

根據預設,TextBoxRichTextBox 都具有使用者於控制項內以滑鼠右鍵按一下即會顯示的內容功能表。內容功能表可以讓使用者剪下、複製或貼上文字 (請見下圖)。

具有內容功能表的 TextBox

您可以建立自訂的內容功能表來覆寫預設的功能表。如需詳細資訊,請參閱 HOW TO:在 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

如需完整範例,請參閱使用工具列建立 RichTextBox 範例。此外,如需用於 RichTextBox 的編輯命令示範,請參閱 EditingCommands 範例

偵測內容變更

通常,每當 TextBoxRichTextBox 中的文字有所變更時,應使用 TextChanged 事件來偵測,而不是使用您預期的 KeyDown。如需範例,請參閱 HOW TO:偵測 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>

範例的程式碼後置如下。

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

請參閱

工作

EditingCommands 範例

編輯檢查程式示範

記事本示範

使用工具列建立 RichTextBox 範例

概念

TextBox 概觀

其他資源

RichTextBox HOW TO 主題