Rich Edit 方塊Rich edit box

您可以使用 RichEditBox 控制項來輸入和編輯包含格式化文字、超連結及影像的 RTF 文件。You can use a RichEditBox control to enter and edit rich text documents that contain formatted text, hyperlinks, and images. 您可以藉由將 IsReadOnly 屬性設定成 true ,使 RichEditBox 變成唯讀。You can make a RichEditBox read-only by setting its IsReadOnly property to true.

取得 Windows UI 程式庫Get the Windows UI Library

WinUI 標誌

Windows UI 程式庫 2.2 或更新版本中有這個控制項使用圓角的新範本。Windows UI Library 2.2 or later includes a new template for this control that uses rounded corners. 如需詳細資訊,請參閱圓角半徑For more info, see Corner radius. WinUI 是 NuGet 套件,其中包含適用於 Windows 應用程式的新控制項和 UI 功能。WinUI is a NuGet package that contains new controls and UI features for Windows apps. 如需詳細資訊 (包括安裝指示),請參閱 Windows UI 程式庫For more info, including installation instructions, see Windows UI Library.

平台 APIRichEditBox 類別 (英文)、 Document 屬性 (英文)、 IsReadOnly 屬性 (英文)、 IsSpellCheckEnabled 屬性 (英文)Platform APIs : RichEditBox class, Document property, IsReadOnly property, IsSpellCheckEnabled property

這是正確的控制項嗎?Is this the right control?

使用 RichEditBox 來顯示和編輯文字檔案。Use a RichEditBox to display and edit text files. 您不會透過您使用其他標準文字輸入方塊的方式,使用 RichEditBox 取得針對您應用程式的使用者輸入內容。You don't use a RichEditBox to get user input into you app the way you use other standard text input boxes. 更確切地說,您會使用它來處理與應用程式分開的文字檔案。Rather, you use it to work with text files that are separate from your app. 您通常會將輸入到 RichEditBox 的文字儲存為 .rtf 檔案。You typically save text entered into a RichEditBox to a .rtf file.

  • 如果多行文字方塊的主要目的為建立唯讀文件 (例如部落格文章或電子郵件內容),而且這些文件需要 RTF,則改為使用 RTF 方塊If the primary purpose of the multi-line text box is for creating read-only documents (such as blog entries or the contents of an email message), and those documents require rich text, use a rich text block instead.
  • 擷取只會消耗且不會再對使用者顯示的文字時,請使用純文字輸入控制項。When capturing text that will only be consumed and not redisplayed to users, use a plain text input control.
  • 針對所有其他案例,請使用純文字輸入控制項。For all other scenarios, use a plain text input control.

如需如何選擇正確文字控制項的詳細資訊,請參閱文字控制項文章。For more info about choosing the right text control, see the Text controls article.

範例Examples

XAML 控制項庫XAML Controls Gallery
XAML controls gallery

如果您已安裝 XAML 控制項庫應用程式,請按一下這裡以開啟應用程式並查看 RichEditBox 的運作情形If you have the XAML Controls Gallery app installed, click here to open the app and see the RichEditBox in action.

此 Rich Edit 方塊已在其中開啟一個 RTF 文件。This rich edit box has a rich text document open in it. 格式和檔案的按鈕不屬於 Rich Edit 方塊的一部分,但您應該至少提供最小一組樣式按鈕,並實作其動作。The formatting and file buttons aren't part of the rich edit box, but you should provide at least a minimal set of styling buttons and implement their actions.

包含已開啟文件的 RTF 方塊

建立 Rich Edit 方塊Create a rich edit box

根據預設,RichEditBox 支援拼字檢查。By default, the RichEditBox supports spell checking. 若要停用拼字檢查工具,請將 IsSpellCheckEnabled 屬性設為 falseTo disable the spell checker, set the IsSpellCheckEnabled property to false. 如需詳細資訊,請參閱拼字檢查的指導方針文章。For more info, see the Guidelines for spell checking article.

您可以使用 RichEditBox 的 Document 屬性取得其內容。You use the Document property of the RichEditBox to get its content. RichEditBox 的內容是 Windows.UI.Text.ITextDocument 物件,與使用Windows.UI.Xaml.Documents.Block 物件做為其內容的 RichTextBlock 控制項不同。The content of a RichEditBox is a Windows.UI.Text.ITextDocument object, unlike the RichTextBlock control, which uses Windows.UI.Xaml.Documents.Block objects as its content. ITextDocument 介面提供的方法可載入文件並儲存為資料流、抓取文字範圍、取得使用中的選取項目、復原和重做變更、設定預設格式化屬性等等。The ITextDocument interface provides a way to load and save the document to a stream, retrieve text ranges, get the active selection, undo and redo changes, set default formatting attributes, and so on.

這個範例說明如何在 RichEditBox 中編輯、載入和儲存 RTF 格式 (rtf) 檔案。This example shows how to edit, load, and save a Rich Text Format (.rtf) file in a RichEditBox.

<RelativePanel Margin="20" HorizontalAlignment="Stretch">
    <RelativePanel.Resources>
        <Style TargetType="AppBarButton">
            <Setter Property="IsCompact" Value="True"/>
        </Style>
    </RelativePanel.Resources>
    <AppBarButton x:Name="openFileButton" Icon="OpenFile"
                  Click="OpenButton_Click" ToolTipService.ToolTip="Open file"/>
    <AppBarButton Icon="Save" Click="SaveButton_Click"
                  ToolTipService.ToolTip="Save file"
                  RelativePanel.RightOf="openFileButton" Margin="8,0,0,0"/>

    <AppBarButton Icon="Bold" Click="BoldButton_Click" ToolTipService.ToolTip="Bold"
                  RelativePanel.LeftOf="italicButton" Margin="0,0,8,0"/>
    <AppBarButton x:Name="italicButton" Icon="Italic" Click="ItalicButton_Click"
                  ToolTipService.ToolTip="Italic" RelativePanel.LeftOf="underlineButton" Margin="0,0,8,0"/>
    <AppBarButton x:Name="underlineButton" Icon="Underline" Click="UnderlineButton_Click"
                  ToolTipService.ToolTip="Underline" RelativePanel.AlignRightWithPanel="True"/>

    <RichEditBox x:Name="editor" Height="200" RelativePanel.Below="openFileButton"
                 RelativePanel.AlignLeftWithPanel="True" RelativePanel.AlignRightWithPanel="True"/>
</RelativePanel>
private async void OpenButton_Click(object sender, RoutedEventArgs e)
{
    // Open a text file.
    Windows.Storage.Pickers.FileOpenPicker open =
        new Windows.Storage.Pickers.FileOpenPicker();
    open.SuggestedStartLocation =
        Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
    open.FileTypeFilter.Add(".rtf");

    Windows.Storage.StorageFile file = await open.PickSingleFileAsync();

    if (file != null)
    {
        try
        {
            Windows.Storage.Streams.IRandomAccessStream randAccStream =
        await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

            // Load the file into the Document property of the RichEditBox.
            editor.Document.LoadFromStream(Windows.UI.Text.TextSetOptions.FormatRtf, randAccStream);
        }
        catch (Exception)
        {
            ContentDialog errorDialog = new ContentDialog()
            {
                Title = "File open error",
                Content = "Sorry, I couldn't open the file.",
                PrimaryButtonText = "Ok"
            };

            await errorDialog.ShowAsync();
        }
    }
}

private async void SaveButton_Click(object sender, RoutedEventArgs e)
{
    Windows.Storage.Pickers.FileSavePicker savePicker = new Windows.Storage.Pickers.FileSavePicker();
    savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;

    // Dropdown of file types the user can save the file as
    savePicker.FileTypeChoices.Add("Rich Text", new List<string>() { ".rtf" });

    // Default file name if the user does not type one in or select a file to replace
    savePicker.SuggestedFileName = "New Document";

    Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();
    if (file != null)
    {
        // Prevent updates to the remote version of the file until we
        // finish making changes and call CompleteUpdatesAsync.
        Windows.Storage.CachedFileManager.DeferUpdates(file);
        // write to file
        Windows.Storage.Streams.IRandomAccessStream randAccStream =
            await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

        editor.Document.SaveToStream(Windows.UI.Text.TextGetOptions.FormatRtf, randAccStream);

        // Let Windows know that we're finished changing the file so the
        // other app can update the remote version of the file.
        Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file);
        if (status != Windows.Storage.Provider.FileUpdateStatus.Complete)
        {
            Windows.UI.Popups.MessageDialog errorBox =
                new Windows.UI.Popups.MessageDialog("File " + file.Name + " couldn't be saved.");
            await errorBox.ShowAsync();
        }
    }
}

private void BoldButton_Click(object sender, RoutedEventArgs e)
{
    Windows.UI.Text.ITextSelection selectedText = editor.Document.Selection;
    if (selectedText != null)
    {
        Windows.UI.Text.ITextCharacterFormat charFormatting = selectedText.CharacterFormat;
        charFormatting.Bold = Windows.UI.Text.FormatEffect.Toggle;
        selectedText.CharacterFormat = charFormatting;
    }
}

private void ItalicButton_Click(object sender, RoutedEventArgs e)
{
    Windows.UI.Text.ITextSelection selectedText = editor.Document.Selection;
    if (selectedText != null)
    {
        Windows.UI.Text.ITextCharacterFormat charFormatting = selectedText.CharacterFormat;
        charFormatting.Italic = Windows.UI.Text.FormatEffect.Toggle;
        selectedText.CharacterFormat = charFormatting;
    }
}

private void UnderlineButton_Click(object sender, RoutedEventArgs e)
{
    Windows.UI.Text.ITextSelection selectedText = editor.Document.Selection;
    if (selectedText != null)
    {
        Windows.UI.Text.ITextCharacterFormat charFormatting = selectedText.CharacterFormat;
        if (charFormatting.Underline == Windows.UI.Text.UnderlineType.None)
        {
            charFormatting.Underline = Windows.UI.Text.UnderlineType.Single;
        }
        else {
            charFormatting.Underline = Windows.UI.Text.UnderlineType.None;
        }
        selectedText.CharacterFormat = charFormatting;
    }
}

選擇文字控制項的正確鍵盤Choose the right keyboard for your text control

為協助使用者使用觸控式鍵盤或螢幕輸入面板 (SIP) 輸入資料,您可以設定文字控制項的輸入範圍,使其符合使用者要輸入的資料類型。To help users to enter data using the touch keyboard, or Soft Input Panel (SIP), you can set the input scope of the text control to match the kind of data the user is expected to enter. 預設鍵盤配置通常適用於處理 RTF 文件。The default keyboard layout is usually appropriate for working with rich text documents.

如需如何使用輸入範圍的詳細資訊,請參閱使用輸入範圍來變更觸控式鍵盤For more info about how to use input scopes, see Use input scope to change the touch keyboard.

可行與禁止事項Do's and don'ts

  • 建立 RTF 方塊時,提供設定樣式按鈕並實作其動作。When you create a rich text box, provide styling buttons and implement their actions.
  • 使用與您的應用程式樣式一致的字型。Use a font that's consistent with the style of your app.
  • 文字控制項的高度必須能夠容納一般輸入。Make the height of the text control tall enough to accommodate typical entries.
  • 不要讓文字輸入控制項的高度隨著使用者輸入增加。Don't let your text input controls grow in height while users type.
  • 使用者只需要單行時,不要使用多行文字方塊。Don't use a multi-line text box when users only need a single line.
  • 使用純文字控制項就足夠時,不要使用 RTF 控制項。Don't use a rich text control if a plain text control is adequate.

取得範例程式碼Get the sample code