Rich Edit 方塊

您可以使用 RichEditBox 控制件來輸入和編輯包含格式化文字、超連結和影像的 RTF 檔。 您可以將 RichEditBox 的 IsReadOnly 屬性設定為 true,讓 RichEditBox 只讀。

這是正確的控制項嗎?

使用 RichEditBox 來顯示和編輯文字檔。 您不會使用 RichEditBox,以使用其他標準文字輸入方塊的方式,將使用者輸入輸入到應用程式中。 相反地,您可以使用它來處理與應用程式分開的文字檔。 您通常會將輸入至 RichEditBox 的文字儲存至.rtf檔案。

  • 如果多行文字方塊的主要目的為建立唯讀文件 (例如部落格文章或電子郵件內容),而且這些文件需要 RTF,則改為使用 RTF 方塊
  • 擷取只會取用且不會重新顯示給使用者的文字時,請使用純文本輸入控件。
  • 針對所有其他案例,請使用純文本輸入控件。

如需如何選擇正確文字控制項的詳細資訊,請參閱文字控制項文章。

建議

  • 建立 RTF 方塊時,提供設定樣式按鈕並實作其動作。
  • 使用與您的應用程式樣式一致的字型。
  • 文字控制項的高度必須能夠容納一般輸入。
  • 不要讓文字輸入控制項的高度隨著使用者輸入增加。
  • 使用者只需要單行時,不要使用多行文字方塊。
  • 使用純文字控制項就足夠時,不要使用 RTF 控制項。

範例

此 RTF 編輯方塊中已開啟 RTF 檔。 格式設定和檔案按鈕不是豐富編輯框的一部分,但您應該至少提供一組最少的樣式按鈕並實作其動作。

A rich text box with an open document

UWP 和 WinUI 2

重要

本文中的資訊和範例已針對使用 Windows 應用程式 SDKWinUI 3 的應用程式進行優化,但通常適用於使用 WinUI 2 的 UWP 應用程式。 如需平臺特定資訊和範例,請參閱 UWP API 參考。

本節包含您在 UWP 或 WinUI 2 應用程式中使用控件所需的資訊。

此控件的 API 存在於 Windows.UI.Xaml.Controls 命名空間中。

我們建議使用最新的 WinUI 2 來取得所有控制件的最新樣式和範本。 WinUI 2.2 或更新版本包含使用此圓角之控件的新範本。 如需詳細資訊,請參閱圓角半徑

建立豐富的編輯框

WinUI 3 資源 應用程式包含大部分 WinUI 3 控制件、特性和功能的互動式範例。 從 Microsoft Store 取得應用程式,或在 GitHub 上 取得原始程式碼

根據預設,RichEditBox 支援拼字檢查。 若要停用拼字檢查程式,請將 IsSpellCheckEnabled 屬性設定為 false。 如需詳細資訊,請參閱 拼字檢查 的指導方針一文。

您可以使用 RichEditBox 的 Document 屬性來取得其內容。 RichEditBox 的內容是 ITextDocument 物件,與使用 Block 物件做為其內容的 RichTextBlock 控件不同。 ITextDocument 介面提供將檔載入和儲存至數據流、擷取文字範圍、取得使用中選取範圍、復原和重做變更、設定預設格式屬性等方式。

此範例示範如何在 RichEditBox 中編輯、載入及儲存 RTF 格式 (.rtf) 檔案。

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

選擇文字控制項的正確鍵盤

為協助使用者使用觸控式鍵盤或螢幕輸入面板 (SIP) 輸入資料,您可以設定文字控制項的輸入範圍,使其符合使用者要輸入的資料類型。 默認鍵盤配置通常適用於使用 RTF 檔。

如需如何使用輸入範圍的詳細資訊,請參閱 使用輸入範圍來變更觸控式鍵盤

取得範例程式碼